Return to Snippet

Revision: 3966
at October 10, 2007 04:02 by natalie


Initial Code
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;

Initial URL
http://notes.natbat.net/2006/12/06/trycatchjavascript/

Initial Description
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.

Initial Title
Failsafe load for attaching stylesheet

Initial Tags
load

Initial Language
JavaScript