Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 203
Lukas Avatar asked Dec 20 '10 10:12

Lukas


People also ask

How can I tell where CSS is coming from?

You may use web inspector in Chrome. Right click on failing element and select inspect element. You should end up with web inspector window with two sections: left is html nodes tree and right is styles and properties of selected node. Failing element should be selected already.

Is CSS loaded synchronously?

With “onload = 'this. media =' all '”, the CSS file is loaded asynchronous and it can be used without a render-blocker effect. To load CSS Files async, you can check the code block below.

What order are CSS files loaded?

Is it depends on size of the CSS file, name or any other parameter ? The external files are loaded the order they are included in the DOM, and imported stylesheets before the 'importer'.


2 Answers

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

like image 70
Lukas Avatar answered Oct 05 '22 23:10

Lukas


Worth knowing that now current versions of Chrome and Firefox fire the onload event on links.

var cssFile = document.createElement("link"); cssFile.setAttribute("rel", "stylesheet"); cssFile.setAttribute("type", "text/css"); // Add event listener cssFile.onload = function(){ console.log('loaded'); } cssFile.setAttribute("href", 'pathToYour.css'); document.getElementsByTagName("head")[0].appendChild(cssFile); 
like image 24
Ben Avatar answered Oct 05 '22 22:10

Ben