Posted By

natalie on 10/10/07


load stylesheet attach domready

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Failsafe load for attaching stylesheet

 / Published in: JavaScript


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. }
  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");
  16. // attempt to add the css and then keep trying till we do
  17. setCSS(css);
  18. css = null;

Report this snippet  


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.