We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

natalie on 10/10/07


Tagged

load stylesheet attach domready


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

inamorix
vali29


Failsafe load for attaching stylesheet


Published in: JavaScript 


URL: http://notes.natbat.net/2006/12/06/trycatchjavascript/

The setTimeout ensures that if there is an issue attaching the link to the bottom of the head (e.g. if the head hasn’t finished loading when the link is trying to be attached) it retries after 100ms. Resetting the css variable to null avoids potential memory leaks.


  1. function setCSS(css) {
  2. try {
  3. // append stylesheet to alter
  4. document.getElementsByTagName("head")[0].appendChild(css);
  5. } catch (e) {
  6. setTimeout(function(){setCSS(css)}, 100);
  7. }
  8. }
  9.  
  10. // create CSS element to set up the page
  11. var css = document.createElement("link");
  12. css.setAttribute("href",path/to/stylesheet);
  13. css.setAttribute("rel","stylesheet");
  14. css.setAttribute("type","text/css");
  15.  
  16. // attempt to add the css and then keep trying till we do
  17. setCSS(css);
  18. css = null;

Report this snippet 

You need to login to post a comment.