Home > CSS > Add CSS to a page dynamically

Add CSS to a page dynamically

 Sometime, we need to add some CSS to a page dynamically.

We can use the following javascript to  add a CSS to a page. This is helful when we are adding/modifying a page in some portal applications like Joomla or Share-point. where we cannot add the CSS to a page in design time.

 

function AddCSS(skinPath)
{
        if(document.createStyleSheet)
       {
            document.createStyleSheet(skinPath);
       }
       else
       
{
              var styles = “@import url(‘ “+skinPath+” ‘);”;
              var newSS=document.createElement(‘link’);
              newSS.rel=‘stylesheet’;
              newSS.href=‘data:text/css,’+escape(styles);
              document.getElementsByTagName(“head”)[0].appendChild(newSS);
       }
}

Advertisements
Categories: CSS Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: