Last active
January 25, 2023 13:07
-
-
Save itsjavi/93cc837dd2213ec0636a to your computer and use it in GitHub Desktop.
JS ScriptLoader using ES6 Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* 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; | |
} | |
} |
Nice, but how to prevent same script from loading multiple times?
@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
Sample usage: