Dynamically Loading Multiple Scripts in Sequence

javascript
Published on December 18, 2020

Multiple Javascript files can be loaded dynamically and executed in a given order by creating <script> element for each of them, and inserting them to the DOM in order of their intended execution.

// scripts to execute in order
let scripts = [
				'script1.js',
				'script2.js',
				'script3.js'
			];

scripts.forEach(function(url) {
	let script = document.createElement('script');
	script.src = url;
	script.async = false;
	document.body.appendChild(script);
});

It is important to set async=false for the created scripts. Otherwise browsers automatically set this attribute to true, and order of execution will not be preserved then.

Knowing When All Scripts Have Been Loaded

The onload event of the <script> element can be used to detect whether it has finished loading. To know when all scripts have finished loading, we can use the concept of Promises.

function loadScript(url) {
	return new Promise(function(resolve, reject) {
		let script = document.createElement('script');
		script.src = url;
		script.async = false;
		script.onload = function() {
			resolve(url);
		};
		script.onerror = function() {
			reject(url);
		};
		document.body.appendChild(script);
	});
}

let scripts = [
				'script1.js',
				'script2.js',
				'script3.js'
			];

// save all Promises as array
let promises = [];
scripts.forEach(function(url) {
	promises.push(loadScript(url));
});

Promise.all(promises)
.then(function() {
	console.log('all scripts loaded');
}).catch(function(script) {
	console.log(script + ' failed to load');
});
  • Function loadScript() inserts the script element and returns a Promise. This Promise is resolved when script is loaded, and rejected when loading fails.
  • Promises for all scripts are saved in an array, and passed to Promise.all() as parameter. This method returns a Promise that is resolved when all input Promises have been resolved. It is rejected when any of the input Promises is rejected.

Useful Resources

In this Tutorial