Posted By

natalie on 10/10/07


Tagged

load stylesheet attach domready


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

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  

Comments

RSS Icon Subscribe to comments
Posted By: sherakama on July 30, 2009

Worked like a charm. Great post. Thanks.

You need to login to post a comment.