Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JS ScriptLoader using ES6 Promises
/*!
* ES6 ScriptLoader snippet
* (c) Javier Aguilar mjolnic.com
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
* Source: https://gist.github.com/mjolnic/93cc837dd2213ec0636a
*/
window.ScriptLoader = function () {
/**
*
* @param {string} url
* @param {object=} attr
* @returns {Promise}
*/
var loader = function (url, attr) {
return new Promise(function (resolve, reject) {
var script = window.document.createElement('script');
script.src = url;
script.async = true;
script.crossOrigin = 'anonymous';
attr = attr || {};
for (var attrName in attr) {
script[attrName] = attr[attrName];
}
script.addEventListener('load', function () {
resolve(script);
}, false);
script.addEventListener('error', function () {
reject(script);
}, false);
window.document.body.appendChild(script);
});
};
/**
* Loads scripts asynchronously
* @param {string|string[]} urls
* @param {object=} attr Other script tag attributes
* @returns {Promise}
*/
this.load = function (urls, attr) {
if (!Array.isArray(urls)) {
urls = [urls];
}
return Promise.all(urls.map(function (url) {
return loader(url, attr);
}));
}
/**
* Loads scripts asynchronously. It supports multiple url arguments, so each one will be loaded right after the
* previous is loaded. This is a way of chaining dependency loading.
*
* @param {string|string[]} urls, ...
* @returns {Promise}
*/
this.loadChain = function (urls) {
var args = Array.isArray(arguments) ? arguments : Array.prototype.slice.call(arguments);
var p = this.require(args.shift());
var self = this;
return args.length ? p.then(function () {
self.requireChain(...args);
}) : p;
}
}
@itsjavi
Copy link
Author

itsjavi commented Dec 4, 2015

Sample usage:

var loader = new ScriptLoader();
loader.load([
    '//code.jquery.com/jquery-2.1.4.min.js',
    '//cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js',
    '//cdnjs.cloudflare.com/ajax/libs/dropbox.js/0.10.3/dropbox.min.js'
]).then(function (scriptElements) {
    console.log(scriptElements.length + ' Scripts Loaded!');
    loader.load([
        '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js',
        'app.js'
    ]);
});

@dziku86
Copy link

dziku86 commented Jan 1, 2021

Nice, but how to prevent same script from loading multiple times?

@itsjavi
Copy link
Author

itsjavi commented Jan 5, 2021

@dziku86 this script is 5 years old I recommend searching other solutions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment