jQuery: loading css on demand + callback if done

How to load multiple CSS files with callback as requested
Note: ithout xdomain permissions, $.get will only load local files

WORKING DEMO
Note that the text “all css loaded” appears after loading but before the CSS is applied. Perhaps another workaround is required to overcome that.

$.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();
        });
    },
});

Usage

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');
});

to force refresh the css files add true

$.getManyCss(cssfiles, function(){
    // do something, e.g.
    console.log('all css loaded');
}, true);

Leave a Comment