Load another JavaScript file from within a JavaScript file

OpenJavaScript 0
Reading Time: < 1 minute 🕑

Last updated: March 24, 2022.

Sometimes, you may want to dynamically load another JavaScript file from within a JavaScript file.

This can be done using the following loadScript function:

function loadScript(src) {
    let script = document.createElement('script');
    script.src = src;
    document.head.append(script);
}

loadScript('myScript.js')

Just pass in the src when calling loadScript. The script will run as soon as it hits the DOM.

And because the script is loaded in JavaScript, its loading can be made conditional upon, for example, the user's screen width:

function loadScript(src) {
    let script = document.createElement('script');
    script.src = src;
    document.head.append(script);
}

if (window.screen.width > 500) {
   loadScript('script.js')
}

Calling a function after loading a script

Want to do something after the script has loaded? Then you can add an onloadFunction call in the loadScript function that fires on the onload event for the script. The onloadFunction function is referenced as the second parameter of loadScript and is defined when it is called:

function loadScript(src, onloadFunction) {
    let script = document.createElement('script');
    script.onload = onloadFunction;
    script.src = src;
    document.head.append(script);
}

loadScript('myScript.js', function() { /* Do something once the script has loaded */ })

Change script loading behavior 🔄

By default, a script loads as if it has the async loading attribute (although this isn't defined). One of the consequences of async loading is that if loadscript is called multiple times, scripts do not wait for each other, and so they may load in an unexpected order.

To change this, set script.async = false. Then each script loaded with loadScript will finish loaded before the next script is loaded:

function loadScript(src) {
    let script = document.createElement('script');
    script.src = src;
    script.async = false; // Removes async behaviour
    document.head.append(script);
}
// Scripts will load in order
loadScript('myScript1.js');
loadScript('myScript2.js');