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?
the idea is: loading html
via xmlhttp
, loading +adding required css-files, then - after anything is finished, display that html
.
any idea?
Thanx!
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(); }); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With