Dean Williams

jQuery: Load CSS with AJAX (all browsers)

You are currently viewing the Mobile Optimized version (AMP), some features may be missing or may not work as expected. Open Full Version.

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 type="text/javascript">
	$(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 type="text/javascript">
	$(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:

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

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips