Failsafe load for attaching stylesheet

/ Published in: JavaScript
Save to your folder(s)

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.

Copy this code and paste it in your HTML
  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

You need to login to post a comment.