How to load CSS stylesheets dynamically with jQuery

Sometimes you may want to load a CSS stylesheet dynamically after your HTML page has loaded and certain conditions are met (for example, if an element with a specific class exists in the DOM). jQuery can help you accomplish that with only a few lines of code.

How to get there:

The HTML:

For this example, let’s say we need to load a stylesheet to format a div tag in the following HTML code:

<html>
<head>
<title>jQuery - Load CSS</title>
</head>
<body>
<div id="container" class="class">
<p>This is a div tag that was formatted using <a href="http://www.jquery.com" alt="Link to jQuery.com">jQuery</a>
</p></div>
</body>
</html>

The CSS:

This will be the CSS code in our sample stylesheet, “style.css”:

#container{
   border: 1px solid #000;
   background-color:#EEE;
   padding:8px;
   margin:8px;
   width: 200px;
}

The jQuery:

These are the jQuery functions we’ll use to get this done:

  • $() wrapper: as the main and most powerful jQuery function, we’ll use it to:
    • Execute code once the document has been loaded
    • Determine whether the #container div element exists in the DOM and, if true,
    • Create new HTML to link the style.css stylesheet to our page
  • append(): this jQuery function allows you to append new HTML code to any element in the DOM. For this example, we’ll attach a new <link> element to the <head> element of our document.

Bringing it all together:

With our HTML and CSS files in place, let’s get this done:

Load jQuery

  • Add the following code between the </body> and </html> tags in your HTML document (Note: your actual path might be different than the one on this example, depending on where your jquery.js file has been stored)
<script type="text/javascript" src="../jquery-1.4.2.min.js"></script>

Add the jQuery code

  • Right under the last line, add the following code:
<script type="text/javascript">

$(document).ready(function(){ //Once the document is ready, run the following code

   if($("#container").size()>0){ //Check if at least one element with the id "#container" exists within the DOM

      $("head").append($("<link rel='stylesheet' href='style.css' type='text/css' media='screen' />")); //if true, append the new <link> element to the <head> element in oor HTML page    }
});

</script>

 

 

* * * UPDATE * * *

Domenico Testa pointed out that the approach above doesn’t work correctly in IE. IE needs the┬á document.createStyleSheet() function to attach new stylesheet after loading the page:

document.createStyleSheet('style.css');

 

So, the final code should be:

<script type="text/javascript">
	$(document).ready(function(){

	if($("#container").size()>0){
			if (document.createStyleSheet){
				document.createStyleSheet('style.css');
			}
			else {
				$("head").append($("<link rel='stylesheet' href='style.css' type='text/css' media='screen' />"));
			}
		}
	});
</script>

View example here »

 

And that should be it. This technique is useful if your page has loaded and you want to load extra CSS files when certain elements exist in the DOM. This can help you save some bandwidth and make your page load faster.

Be Sociable, Share!

    20 Comments

    1. Domenico Testa

      This example does not work as expected under Internet Explorer.
      I’m testing using version 8 but i guess it will not work on former versions either.

      Reply
      • Hi Domenico,

        You are right, the original script didn’t work correctly. IE needs new stylesheets to be added to the DOM via document.createStylesheet(). Please see the updated portion of this post above for the rest of the code.

        Thanks!

        Reply
    2. Holy cow! This is the only solution for IE that I have been able to find the on the web, thanks!!

      Reply
    3. this article is safe my life!!! . Thank you !! ­čśÇ

      Reply
    4. Thanks for sharing, very useful!

      Reply
    5. Hi, it’s work fine. Tks

      Reply
    6. Giovanni Pires da Silva

      Isn’t necessary know when it was loaded like in the JQuery getScript? If so, how can I know when it’s loaded?

      Reply
      • Hey Giovanni, thanks for posting!

        I’m not completely sure I understand the question, but here it goes.

        I’m assuming you are wondering about something similar to a success parameter or callback function like in jQuery.getScript(), which tells you whether the file was loaded or not. Unfortunately, there isn’t any in this example.

        In the article, the script is meant to load an extra CSS file once it’s been determined via jQuery that an element (‘#container’ in this case) exists within the DOM. In the example, that process happens once the page has been fully loaded.

        Visually, you will know the CSS file has been loaded once the CSS is applied to your page. Now, if you want to know whether that specific CSS file has been loaded, you could check for it:


        //place this at the end of the script
        if($('link[href="style.css"]').size()>0){alert ('loaded')}

        This will check whether the file “style.css” can now be found in the DOM, and will alert “loaded” if found.

        I hope that helps. Please fee free to let me know if you have any other questions!

        Reply
    7. Another solution, with a slightly different if statement, can be found at this question on StackOverflow.

      Reply
    8. Thanks for sharing, really helpfull!

      Reply
    9. thats awesome stuff, your don’t know how much you have done for me.

      Reply
    10. Usually speed problems on the use jquery.. I’ll try it for my blog

      Reply

    Trackbacks/Pingbacks

    1. […] much hair-tearing out, I stumbled across this post┬áby┬áVidal Quevedo. And – wouldn’t you know it? – it transpires there’s a […]

    Leave a Comment