jQuery: Load CSS with AJAX (all browsers)

I was recently looking for a solution for loading style sheets dynamically into a web page, but I was also after knowing when the style sheet was loaded so I could stop showing my custom loading bar.

I decided the best way to do this was to load the file with jQuery Ajax, which would give me the “success” call-back and allow me to pick up on failures and etc.

This is the code I originally implemented:

<script >
$(document).ready(function(){
$.ajax({
url:"style.css",
dataType:"script",
success:function(data){
$("<style></style>").appendTo("head").html(data);
//loading complete code here
}
});
});
</script>

 

However the above code will not work in IE6 – IE7 –IE8 – Safari and probably more browsers, which is definitely NO GOOD! Especially when it does not work in the latest Safari!

I managed to find a work around, which in my opinion does EXACTLY THE SAME THING, but what makes all the browsers happy, makes me happy:

<script >
$(document).ready(function(){
$.ajax({
url:"style.css",
dataType:"script",
success:function(data){
$("head").append("<style>" + data + "</style>");
//loading complete code here
}
});
});
</script>

 

This works in all the following browsers I have tested it in:

  • Internet Explorer 6, 7, 8, 9
  • Safari (latest)
  • Google Chrome (latest)
  • Firefox (latest)
  • Opera (latest)

Please drop a comment if this helped you or if you have found a browser it is not compatible with.

Facebooktwitterredditpinterestlinkedinmail
Author: Dean WilliamsI'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
, , ,
2 1 vote
Article Rating
Subscribe
Notify of
7 Comments
Inline Feedbacks
View all comments

Hi Deano
i just found your website and this jquery is, i think, exactly what i'm looking for :razz: … but have you got an online demo, this will be very useful for me (to be honest, i'm not sure to know how i can implement this on my xwiki pages using jquery :oops: ).
Thanks you!
regards
Jerome

Hi, I want to call a css file using a custom code module for joomla, am i going to use this code as the link?

Hi Deano,

Just wanted to say this is a very elegant solution. Found your code after a little google-fu and love it. Bookmarked, thank you.

Nice. But you could also create a tag in you primary page as :
<style id="csscontainer" > </style>

and then
$(document).ready(function(){
$("#csscontainer").load("http://yoursite.com/site.css");
});

The difference with the two examples is that "$("").appendTo("head").html(data);" adds the data to the style tag after it has been added to the DOM. I would guess that "$("").html(data).appendTo("head");" would work better.

That sort of worked. An important modification I did to make it work is "DON'T INCLUDE THE DATATYPE" attribute.