我想按需加载CSS文件(通过例如运行XML HTTP请求,返回要加载的CSS文件),例如style1.css,style2.css ..
那么jQuery(或插件)有没有这种方法呢?
这个想法是:加载htmlvia xmlhttp,加载+添加所需的 css文件,然后 - 在完成任何事情后,显示它html.
任何的想法?
感谢名单!
Pop*_*les 23
如何使用所请求的回调加载多个 CSS文件请注意,如果没有xdomain权限,$ .get将只加载本地文件
$.extend({
getManyCss: function(urls, callback, nocache){
if (typeof nocache=='undefined') nocache=false; // default don't refresh
$.when.apply($,
$.map(urls, function(url){
if (nocache) url += '?_ts=' + new Date().getTime(); // refresh?
return $.get(url, function(){
$('<link>', {rel:'stylesheet', type:'text/css', 'href':url}).appendTo('head');
});
})
).then(function(){
if (typeof callback=='function') callback();
});
},
});
Run Code Online (Sandbox Code Playgroud)
var cssfiles = ['/ css/normalize.css?jobofferinsidebar','/ css/trip.css?jobofferinsidebar'];
$ .getCss(cssfiles,function(){console.log('all css loaded');}); 用法
var cssfiles=['https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', 'https://stackpath.bootstrapcdn.com/bootswatch/4.3.1/cerulean/bootstrap.min.css'];
$.getManyCss(cssfiles, function(){
// do something, e.g.
console.log('all css loaded');
});
Run Code Online (Sandbox Code Playgroud)
强制刷新css文件添加true
$.getManyCss(cssfiles, function(){
// do something, e.g.
console.log('all css loaded');
}, true);
Run Code Online (Sandbox Code Playgroud)
小智 9
@Popnoodles给出的答案是不正确的,因为在加载所有项之后不执行回调,而是在$ .each循环结束时执行.原因是,该$.each操作不返回Deferred对象(预期的对象$.when).
这是一个更正的例子:
$.extend({
getCss: function(urls, callback, nocache){
if (typeof nocache=='undefined') nocache=false; // default don't refresh
$.when.apply($,
$.map(urls, function(url){
if (nocache) url += '?_ts=' + new Date().getTime(); // refresh?
return $.get(url, function(){
$('<link>', {rel:'stylesheet', type:'text/css', 'href':url}).appendTo('head');
});
})
).then(function(){
if (typeof callback=='function') callback();
});
}
});
Run Code Online (Sandbox Code Playgroud)
我将如何加载它:
$(document).ready( function() {
var css = jQuery("<link>");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "path/to/file/style.css"
});
$("head").append(css);
});
Run Code Online (Sandbox Code Playgroud)