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.

See also  Scalable Vector Iconic Font - fontisto

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

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

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

// append new script to html

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.

See also  Flat Social Share Buttons In Pure CSS

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;

		// 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;


req.open('GET', "https://usefulangle.com/post/101/javascript-file.js"); 

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

See also  Adding Elements to an Array with Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *