Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link element onload

Is there anyway to listen to the onload event for a <link> element?

F.ex:

var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'styles.css';  link.onload = link.onreadystatechange = function(e) {     console.log(e); }; 

This works for <script> elements, but not <link>. Is there another way? I just need to know when the styles in the external stylesheet has applied to the DOM.

Update:

Would it be an idea to inject a hidden <iframe>, add the <link> to the head and listen for the window.onload event in the iframe? It should trigger when the css is loaded, but it might not guarantee that it's loaded in the top window...

like image 503
David Hellsing Avatar asked Jun 20 '10 08:06

David Hellsing


1 Answers

Today, all modern browsers support the onload event on link tags. So I would guard hacks, such as creating an img element and setting the onerror:

if !('onload' in document.createElement('link')) {   imgTag = document.createElement(img);   imgTag.onerror = function() {};   imgTag.src = ...; }  

This should provide a workaround for FF-8 and earlier and old Safari & Chrome versions.

minor update:

As Michael pointed out, there are some browser exceptions for which we always want to apply the hack. In Coffeescript:

isSafari5: ->   !!navigator.userAgent.match(' Safari/') &&       !navigator.userAgent.match(' Chrom') &&       !!navigator.userAgent.match(' Version/5.')  # Webkit: 535.23 and above supports onload on link tags. isWebkitNoOnloadSupport: ->   [supportedMajor, supportedMinor] = [535, 23]   if (match = navigator.userAgent.match(/\ AppleWebKit\/(\d+)\.(\d+)/))     match.shift()     [major, minor] = [+match[0], +match[1]]     major < supportedMajor || major == supportedMajor && minor < supportedMinor 
like image 78
mlangenberg Avatar answered Sep 21 '22 13:09

mlangenberg