Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  152] [ 7]  / answers: 1 / hits: 25975  / 14 Years ago, wed, april 14, 2010, 12:00:00

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?


PS: I may not use any framework in solving this.


More From » dom-events

 Answers
23

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.


[#97078] Monday, April 12, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
phoebea

Total Points: 607
Total Questions: 100
Total Answers: 78

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
;