jQuery: loading css on demand + callback if done

Fuxi picture Fuxi · Aug 17, 2010 · Viewed 18.2k times · Source

I want to load CSS files on demand (by eg. running an XML HTTP request which returns the CSS files to be loaded) for example style1.css, style2.css ..

So is there a way in jQuery (or a plugin) to this?

  • bulk-loading several files + adding all those CSS-files into the dom
  • when finished loading: firing a callback (like alerting "all stylesheets are finished loaded!");

the idea is: loading html via xmlhttp, loading +adding required css-files, then - after anything is finished, display that html.

any idea?

Thanx!

Answer

Popnoodles picture Popnoodles · Jul 25, 2013

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