Load external css file like scripts in jquery which is compatible in ie also
Is there a way to load external CSS files, like we load JS file by using .getScript method and also use the callback function like in .getScript
$("<link/>", {
rel: "stylesheet",
type: "text/css",
href: "/styles/yourcss.css"
}).appendTo("head");
This Works in FireFox and similar but not in IE.
In jQuery 1.4:
$("<link/>", {
rel: "stylesheet",
type: "text/css",
href: "/styles/yourcss.css"
}).appendTo("head");
http://api.jquery.com/jQuery/#jQuery2
Quick function based on responses.
loadCSS = function(href) {
var cssLink = $("<link>");
$("head").append(cssLink); //IE hack: append before setting href
cssLink.attr({
rel: "stylesheet",
type: "text/css",
href: href
});
};
Usage:
loadCSS("/css/file.css");
$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "address_of_your_css"
});
I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('<style type="text/css">\n' + data + '</style>').appendTo("head");
}
});
In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:
// Remove old style
$("head").children().each(function(index, ele) {
if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
$(ele).remove();
return false; // Stop iterating since we removed something
}
});