views:

166

answers:

3

hello everyone,

i'm trying to attach an event handler to the load event of a link tag, to execute some code after a stylesheet has loaded.

new_element = document.createElement('link');
new_element.type = 'text/css';
new_element.rel = 'stylesheet';
new_element.href = 'http://domain.tld/file.css';
new_element.addEventListener('load', function() { alert('foo'); }, false);
document.getElementsByTagName('head')[0].appendChild(new_element)

i have tried onreadystatechange as well

new_element.onreadystatechange = function() { alert('foo'); }

unfortunately neither approach results in an alert being triggered.. Furthermore, new_element.onload is null after registering a handler for the 'load' event with addEventListener.. is that normal?

thanks, andrew

ps: i may not use any framework in solving this

+1  A: 

An href does not have a load event you need to apply your stuff as the page itself loads e.g.

window.onload = function(){
//code here

}

use the function on this page: http://www.dustindiaz.com/top-ten-javascript/

to add the event the body element (in line would be )

matpol
Thanks- are you saying tossing a stylesheet link tag in the header will cause window.onload to fire after the stylesheet loads ?i've tried this just right now and it did not. Also I'm already running from a window.onload handler.What i'm trying to do is, after the page has loaded (window.onload) load a css (createElement('link')) , after which load some javascript (createElement('script'))The bottom line is, the script that is loaded last, creates nodes that need some css classes to be already loaded
pgn
the javascript loads/runs once the whole page has completed loading so you can only modify the dom once this has happened so you need to run any scripts using the onload event handler which can only be attached to the body element. So all you code needs run in the onload event handler.
matpol
+2  A: 

Even if you add an inline:

<link rel="stylesheet" type="text/css" href="foo.css" onload="alert('xxx')"/>

It won't fire in FireFox as there isn't an onload event for link elements. (It will work in IE)

Alex K.
+2  A: 

For CSS stylesheets (not LINK elements in general) i'm using manual interval, by poking it's rules length. It works crossbrowser (AFAIT).

try {
  if ( cssStylesheet.sheet && cssStylesheet.sheet.cssRules.length > 0 )
    cssLoaded = 1;
  else if ( cssStylesheet.styleSheet && cssStylesheet.styleSheet.cssText.length > 0 )
    cssLoaded = 1;
  else if ( cssStylesheet.innerHTML && cssStylesheet.innerHTML.length > 0 )
    cssLoaded = 1;
}
catch(ex){}

In code above, the cssStylesheet is DOMElement.

Tobiasz Cudnik