// Create new script elementconst script = document.createElement('script');script.src = '/path/to/js/file.js';// Append to the `head` elementdocument.head.appendChild(script);
// Create new script element...script.addEventListener('load', function() {// The script is loaded completely// Do something});// Append to the `head` element...
arrayOfJs
, in order.// Load a script from given `url`const loadScript = function (url) {return new Promise(function (resolve, reject) {const script = document.createElement('script');script.src = url;script.addEventListener('load', function () {// The script is loaded completelyresolve(true);});document.head.appendChild(script);});};// Perform all promises in the orderconst waterfall = function (promises) {return promises.reduce(function (p, c) {// Waiting for `p` completedreturn p.then(function () {// and then `c`return c().then(function (result) {return true;});});},// The initial value passed to the reduce methodPromise.resolve([]));};// Load an array of scripts in orderconst loadScriptsInOrder = function (arrayOfJs) {const promises = arrayOfJs.map(function (url) {return loadScript(url);});return waterfall(promises);};
loadScriptsInOrder
function returns a Promise
indicates whether all scripts are loaded successfully:loadScriptsInOrder(['/path/to/file.js', '/path/to/another-file.js', '/yet/another/file.js']).then(function () {// All scripts are loaded completely// Do something});