Load a JavaScript File on the Fly

on in JavaScript DOM
Last modified on

Similar to my previous article on how to add/inject a CSS stylesheet using Vanilla JavaScript, this is how you load a JavaScript file on demand and execute any dependent functions.

function loadFile(filePath) {
    // Create a <script> tag, set its source
    let scriptTag = document.createElement('script');

    // And listen to it
    scriptTag.onload = function (loadEvent) {
        // This function is an event handler of the script tag
        handleEvent();
    }

    // Make sure this file actually loads instead of a cached version
    // Add a timestamp onto the URL (i.e. file.js?bust=12345678)
    let cacheBuster = '?bust=' + new Date().getTime();

    // Set the type of file and where it can be found
    scriptTag.type = 'text/javascript';
    scriptTag.src = filePath + cacheBuster;

    // Finally add it to the <head>
    document.getElementsByTagName('head')[0].appendChild(scriptTag);
}

function handleEvent() {
    console.log('The file has been loaded. Do something else.');

    // More code here
}

// Usage
loadFile('/path/to/file.js');

Related posts