jQuery:如果完成,按需加载css +回调

Fux*_*uxi 30 css jquery load

我想按需加载CSS文件(通过例如运行XML HTTP请求,返回要加载的CSS文件),例如style1.css,style2.css ..

那么jQuery(或插件)有没有这种方法呢?

  • 批量加载多个文件+将所有这些CSS文件添加到dom中
  • 完成加载时:触发回调(如警告"所有样式表已完成加载!");

这个想法是:加载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)

  • +1.对于其他想知道的人:解决方案在加载css时不会触发回调(如问题中所要求的).但是由于事先获取了资源,因此当资源在浏览器缓存中时,$ .get()结束后触发的回调将立即触发.确实很好的解决方案,应该是公认的答案. (3认同)

小智 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)


Whi*_*hit 7

我将如何加载它:

$(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)

  • -1答案,因为它只涵盖了问题的一半,这很容易.困难的是css资源加载后的回调 (6认同)
  • 是的,$(document).ready事件将在jQuery加载后触发. (5认同)
  • 这只回答了OP问题的一半:另一半是"完成加载后触发回调".不幸的是,将.load(function(){})添加到创建的链接并不会减少芥末... (5认同)