Loading External Javascript Files with Javascript

It is sometimes required to load an external Javascript file on demand, like when the user clicks on a button, a Javascript plugin needs to be loaded. Once it is loaded the application can use the plugin.

Loading Javascript in this way is also beneficial because it improves the loading time of the page (unnecessary scripts are not loaded while webpage is being loaded). Also because resources are loaded on demand, it ensures a 100% utilization of resources.

This tutorial shows 2 ways in which you can download Javascript files. Somewhat they same use the same logic, but with the second method you can get the exact progress percent of the script being downloaded, which may be useful in enhancing the user experience.

Method 1 : Creating a New Script Element

This method uses the document.createElement to create a new <script> tag, and append it in the page.

Advantage : Javascript file can be from the same or different domain

Disadvantage : Cannot get loading percentage

// create new script tag
var script = document.createElement('script');

// set "src" of script tag
// can be relative or full url
script.src = 'javascript-file.js';

// Loaded successfully
script.onload = function() {
	
};

// Loading failed
script.onerror = function() {
	
};

// append new script to html
document.body.appendChild(script);

Method 2 : Downloading Javascript File with AJAX Request

This method also involves creating a new <script> tag, but the source of the script is downloaded through AJAX. After downloading the source is added as the contents of the new script tag.

Advantage : Can get the progress of the downloading file

Disadvantage : For cross-domain files, it needs CORS headers, otherwise the browser Cross-Origin Policy will not allow the script to run

var req = new XMLHttpRequest();

req.addEventListener('readystatechange', function(e) {
	if(req.readyState == 2 && req.status == 200) {
		// Download will start
	}
	else if(req.readyState == 3) {
		// Download is happenning
	}
	else if(req.readyState == 4) {
		// Downloading has finished

		var script = document.createElement('script');
		script.innerHTML = req.response;
		
		document.body.appendChild(script);

		// script has loaded
		// perform next steps with the loaded javascript file
	}
});

// progress percent of file
req.addEventListener('progress', function(e) {
	if(e.lengthComputable === true) {
		var download_percent = (e.loaded / e.total)*100;
		console.log(download_percent);
	}
});

req.responseType = 'text';

req.open('GET', 'javascript-file.js'); 
    
req.send(); 

Note that the onload and onerror event handlers won't work in this case because the Javascript is essentially inline here.

Dynamically Loading Fonts with Javascript
Loading CSS Files with Javascript