Add CSS Rule to Stylesheet Dynamically with Javascript

Before couple of years we were in impression that stylesheet should only be static but with CSS pre-processors like SASS & LESS, we came to know that it can also be Objective. But recently I come to know that with javascript we can also add stylesheets on the fly while page is rendering.

Now-a-days We are finding a way to load web page faster everyday. As Javascript is client side scripting language we are trying to load elements via javascript to reduce page load time.

In this post I will show, how we can add stylesheet & CSS rules to stylesheet dynamically with javascript.

Adding Stylesheet

Let’s add a new stylesheet in the <head> tag of our page using javascript. It is as simple as we add any new html element in the page. First get the <head> tag and then add stylesheet in it.

var head = document.head;

Create stylesheet element and append it in head variable we have just created:

var style = document.createElement("style");

style.id = "dynamic-style";
style.media = "screen";
style.type = "text/css";

head.appendChild(style);

We can also add external stylesheet in <link> tag as below:

var link = document.createElement("link");

link.id = "dynamic-link";
link.href = "path-to-external-css-file"
link.media = "screen";
link.type = "text/css";

head.appendChild(link);

Adding New CSS Rule

Now lets add new CSS rules in dynamically added stylesheet above. In order to do that we first need to get the stylesheet in which we want to add new rule.

var styles = document.stylesheets;

The line above will get you all the stylesheets attached to the page which will return an array as:

StyleSheetList {0: CSSStyleSheet, 1: CSSStyleSheet, 2: CSSStyleSheet, 3: CSSStyleSheet, 4: CSSStyleSheet, 5: CSSStyleSheet, 6: CSSStyleSheet, 7: CSSStyleSheet, 8: CSSStyleSheet, 9: CSSStyleSheet, 10: CSSStyleSheet, 11: CSSStyleSheet, length: 12}

You can drill down in the stylesheet to get the individual stylesheet just as we work with arrays. Code below shows the properties returned by first stylesheet (style[6]).

console.log(style[6]);

// Returns
CSSStyleSheet {
   cssRules: CSSRuleList
   disabled: false
   href: "http://ashishuideveloper.in/wp-content/themes/hueman/style.css?ver=4.2.2"
   media: MediaList
   ownerNode: link#style-css
   ownerRule: null
   parentStyleSheet: null
   rules: CSSRuleList
   title: null
   type: "text/css"
   __proto__: CSSStyleSheet
}

Now let’s add new CSS Rule to the stylesheet that we have got in the style variable. But before we add new CSS rule to this stylesheet, lets find out that this stylesheet is for the screen and not for the print media. We can find this by getting the value of media property.

style[6].media.metaText

// Returns
"all"

Now as we got the stylesheet we want to add new rules, lets add it:

style[6].addRule(".navigation li", "border: 1px solid #f00", 1);

The code above will add the CSS style for .navigation list. addRule method accepts 3 parameters,

  1. element on which the rule shell apply
  2. CSS style which we need to apply
  3. 1 represents at which to insert the rule

Whenever the page gets loaded the DOM will not go to find and match the elements to apply CSS, which will save time in page rendering. Remember we are adding dynamic CSS rule here so it will get affected to respective element when it is available on the page.

WebKit Browsers

But this method is not working with WebKit browsers, we need hack them to add the CSS rule properly, but that’s an easy task.

style[6].insertRule(".navigation li {border: 1px solid #f00}", 1);

As you can see, for WebKit browsers we need to have only 2 parameters and the method we need to call is insertRule. It is same as in we write our normally in .css file.

Function for all Browsers

Let’s combine both the methods in one function so we can apply the CSS rule on each browsers.

var customCSSRule = function(style, element, rules){
   if("addRule" in style) {
      style.addRule(element, rules, 1);
   } else if("insertRule" in style) {
      style.insertRule(element + "{" + rules + "}", 1);
   }
};

customCSSRule(style[6], ".navigation li", "border: 1px solid #f00");

So with the help of the function above we have apply CSS rule to the stylesheet for all the browsers.

Conclusion

I am very much sure adding stylesheet or CSS Rule dynamically will definitely help in working on projects. It is always better to know the strength of the javascript to make work easier. You can read more on adding CSSRule @ developer.mozilla.org.

Web/ UI & Front-end developer based in Ahmedabad, GJ, India. Here to help/ discuss community to spread web awareness.

1 comments On Add CSS Rule to Stylesheet Dynamically with Javascript

Leave a reply:

Your email address will not be published.