We all know and love Asset.js from MooTools-more. It affords you lazyloading by providing Asset.javascript, Asset.image, Asset.images and Asset.css. However, sometimes you need more precision when bringing in external scripts as dependencies.
Hence I created my own Asset.javascripts – based losely on a coupling of Asset.images and Asset.javascript but providing sequential asynchronous loading.
Asset.javascripts = function(sources, options) { // load an array of js dependencies and fire events as it walks through options = Object.merge({ onComplete: Function.from, onProgress: Function.from }, options); var counter = 0, todo = sources.length; var loadNext = function() { if (sources[0]) source = sources[0]; Asset.javascript(source, { onload: function() { counter++; options.onProgress.call(this, counter, source); sources.erase(source); if (counter == todo) options.onComplete.call(this, counter); else loadNext(); } }); }; loadNext(); };
Eg. usage with Arian’s DatePicker class, which uses multiple files that need to be loaded in their right order:
if (!window.Picker) { new Asset.javascripts([ "/js/mylibs/Locale.en-US.DatePicker.js", "/js/mylibs/Picker.js", "/js/mylibs/Picker.Attach.js", "/js/mylibs/Picker.Date.js" ], { onComplete: function() { new Asset.css("/js/mylibs/datepicker.css"); new Asset.css("/js/mylibs/datepicker_dashboard/datepicker_dashboard.css"); doDates(); } }); } else { doDates(); }
Have fun.
GitHub flavoured markdown enabled.