Posted By

natalie on 10/10/07


Tagged

load stylesheet attach domready


Versions (?)


Advertising

Submit Site


Who likes this?

2 people have marked this snippet as a favorite

inamorix
vali29


Failsafe load for attaching stylesheet


Published in: JavaScript 



Website Promotion
DIRECTORY
is a crucial factor for all websites that need to gain better organic search engine rankings and increase website traffic.
Submitting your website as part of your Web Promotion strategy to our SEO friendly and high traffic Business Directory for review is an excellent way to gain a valuable backlink and increase your websites visibility online.

Submit Site


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.

Expand | Embed | Plain Text
  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.

Download royalty free graphics