/ 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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function setCSS(css) { try { // append stylesheet to alter document.getElementsByTagName("head")[0].appendChild(css); } catch (e) { setTimeout(function(){setCSS(css)}, 100); } } // create CSS element to set up the page var css = document.createElement("link"); css.setAttribute("href",path/to/stylesheet); css.setAttribute("rel","stylesheet"); css.setAttribute("type","text/css"); // attempt to add the css and then keep trying till we do setCSS(css); css = null;
URL: http://notes.natbat.net/2006/12/06/trycatchjavascript/