Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external css file like scripts in jquery which is compatible in ie also

Tags:

jquery

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.

like image 662
Starx Avatar asked Apr 21 '10 18:04

Starx


People also ask

Can I use jquery in CSS file?

You mean you want to add Javascript to a CSS file? If that's the case, then you can't. Only CSS in CSS files :) You'll have to deal with some sort of master page which holds that js file.


2 Answers

In jQuery 1.4:

$("<link/>", {    rel: "stylesheet",    type: "text/css",    href: "/styles/yourcss.css" }).appendTo("head"); 

http://api.jquery.com/jQuery/#jQuery2

like image 103
RedWolves Avatar answered Nov 12 '22 10:11

RedWolves


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"); 
like image 33
xgMz Avatar answered Nov 12 '22 08:11

xgMz