jQuery: loading css on demand + callback if done jQuery: loading css on demand + callback if done jquery jquery

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


The answer given by @Popnoodles is not correct because the callback is not executed after all items have been loaded, but rather when the $.each loop is finished. The reason is, that $.each operation does not return a Deferred object (which is expected by $.when).

Here is a corrected example:

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


Here is how I would load it:

$(document).ready( function() {    var css = jQuery("<link>");    css.attr({      rel:  "stylesheet",      type: "text/css",      href: "path/to/file/style.css"    });    $("head").append(css);});