加载外部 css 文件,如 jquery 中的脚本,在 ie 中也兼容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2685614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load external css file like scripts in jquery which is compatible in ie also
提问by Starx
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
有没有办法加载外部 CSS 文件,就像我们使用 .getScript 方法加载 JS 文件一样,也可以使用 .getScript 中的回调函数
$("<link/>", {
rel: "stylesheet",
type: "text/css",
href: "/styles/yourcss.css"
}).appendTo("head");
This Works in FireFox and similar but not in IE.
这适用于 FireFox 和类似但不适用于 IE。
回答by RedWolves
In jQuery 1.4:
在 jQuery 1.4 中:
$("<link/>", {
rel: "stylesheet",
type: "text/css",
href: "/styles/yourcss.css"
}).appendTo("head");
回答by xgMz
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");
回答by Raul Agrait
$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "address_of_your_css"
});
回答by Ed Bayiates
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:
我认为 OP 想要做的是异步加载样式表并添加它。这对我在 Chrome 22、FF 16 和 IE 8 中适用于以文本形式存储的 CSS 规则集:
$.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:
就我而言,有时我还希望加载的 CSS 替换以前以这种方式加载的 CSS。为此,我在开头放了一条注释,说“/* Flag this ID=102 */”,然后我可以这样做:
// 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
}
});
回答by tmsimont
//load css first, then print <link> to header, and execute callback
//just set var href above this..
$.ajax({
url: href,
dataType: 'css',
success: function(){
$('<link rel="stylesheet" type="text/css" href="'+href+'" />').appendTo("head");
//your callback
}
});
For Jquery 1.2.6 and above ( omitting the fancy attributes functions above ).
对于 Jquery 1.2.6 及更高版本(省略上面的花哨属性函数)。
I am doing it this way because I thinkthat this will ensure that your requested stylesheet is loaded by ajax before you try to stick it into the head. Therefore, the callback is executed after the stylesheet is ready.
我这样做是因为我认为这将确保您请求的样式表在您尝试将其粘贴到头部之前由 ajax 加载。因此,回调在样式表准备好后执行。
回答by abalter
Based on your comment under @Raul's answer, I can think of two ways to include a callback:
根据您在@Raul 的回答下的评论,我可以想到两种包含回调的方法:
- Have
getScript
call the file that loads the css. - Load the contents of the css file with AJAX, and append to
<style>
. Your callback would be the callback from$.get
or whatever you use to load the css file contents.
- 已
getScript
调用文件加载的CSS。 - 使用 AJAX 加载 css 文件的内容,并附加到
<style>
. 您的回调将是来自$.get
或用于加载 css 文件内容的任何回调。
回答by Willster
Here is a function that will load CSS files with a success or failure callback. The failure callback will be called just once, if one or more resources fail to load. I think this approach is better than some of the other solutions because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).
这是一个将通过成功或失败回调加载 CSS 文件的函数。如果一个或多个资源加载失败,则失败回调将只调用一次。我认为这种方法比其他一些解决方案更好,因为使用 HREF 将元素插入 DOM 会导致额外的浏览器请求(尽管请求可能来自缓存,具体取决于响应标头)。
function loadCssFiles(urls, successCallback, failureCallback) {
$.when.apply($,
$.map(urls, function(url) {
return $.get(url, function(css) {
$("<style>" + css + "</style>").appendTo("head");
});
})
).then(function() {
if (typeof successCallback === 'function') successCallback();
}).fail(function() {
if (typeof failureCallback === 'function') failureCallback();
});
}
Usage as so:
用法如下:
loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
function() {
alert("All resources loaded");
}, function() {
alert("One or more resources failed to load");
});
Here is another function that will load both CSS andjavascript files:
这是另一个将加载 CSS和javascript 文件的函数:
function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {
$.when.apply($,
$.map(urls, function(url) {
if(url.endsWith(".css")) {
return $.get(url, function(css) {
$("<style>" + css + "</style>").appendTo("head");
});
} else {
return $.getScript(url);
}
})
).then(function() {
if (typeof successCallback === 'function') successCallback();
}).fail(function() {
if (typeof failureCallback === 'function') failureCallback();
});
}
回答by user2044673
$("#pageCSS").attr('href', './css/new_css.css');
$("#pageCSS").attr('href', './css/new_css.css');