Is there any way to detect when a CSS file has been fully loaded?

Lukas picture Lukas · Dec 20, 2010 · Viewed 17.3k times · Source

I've been testing a lot of lazy-loaders for JavaScript and CSS that insert <script> and <link> tags to load files. However the problem is, that <link> tags don't fire onload so it's difficult to detect when they're loaded. The only workaround I found for this is to set display: none; (in the CSS file that is to be loaded) on a dummy element and poll that element to check when it has been set to display: none. But that, apart from being ugly, of course only works for a single CSS file.

So I was wondering; Is there any other way to detect if a CSS file has been loaded?

Answer

Lukas picture Lukas · Dec 22, 2010

edit: It should be noted that browser support for onload events on CSS files has improved since my original answer. It is not fully supported though, so my answer below still has some relevance. Here is a compatibility chart, not sure how legit the source is though.

Ok, I finally found a solution.

This guy http://tugll.tugraz.at/96784/weblog/9080.html inserts link-tags and polls document.styleSheets[index].rules until it is no longer undefined (where index of course is the index of the newly inserted file). Unfortunately his code is buggy and only works with Safari & FF. So I fixed the bugs, added functionality for Opera and Internet Explorer and even added features for adding multiple CSS and JS files and 1 final callback (when all files are loaded) in a sweet and simple lazyloader-function. The result can be found here:

https://github.com/LukasBombach/Lazyloader