Dynamic CSS Loading with jQuery 1.4: Cross-Browser Problem Solved

May 20th, 2010 posted by admin

Loading an external CSS stylesheet with jQuery is cake.  But in version 1.4 it stopped working in IE. Specifically, doing this doesn’t work:

$('<link href="/path/to/stylesheet.css" rel="stylesheet" type="text/css" />').appendTo("head");

After investigating and Googling this a bit, I discovered that this technique does work:

var $link = $('<link/>').appendTo("head");
$link.attr({
	href : "/path/to/stylesheet.css",
	rel  : "stylesheet",
	type : "text/css"
});

However, this doesn’t work in Opera (only the latest version tested).

The solution is perhaps to simple to bother writing up, but here it is anyway:

$('<link href="/path/to/stylesheet.css" rel="stylesheet" type="text/css" />').appendTo("head");
$link.attr({
	href : "/path/to/stylesheet.css",
	rel  : "stylesheet",
	type : "text/css"
});