How to load JavaScript file dynamically?

The EcmaScript (ES6) since 2015, JavaScript has ES6 modules. This ES6 module is a standard to import modules in Node.js. The ES6 module is also supported by most modern browsers.

JavaScript had no import, include, or require before the arrival of EcmaScript. Many developers tried many different approaches to load files dynamically.

The JavaScript can be on a remote server. The browser evaluates the code. The <script> tag can be injected into either inside <head> tag, or inserted before closing the </body> tag.

# Example inject file inside head tag
(function() {
    const scriptTag = document.createElement('script');
    scriptTag.src = '<jsfile-source>';
    scriptTag.async = 'true';
    document.head.appendChild(scriptTag);
}());

We can write a generic function load or append resource in JavaScript using the following function:

export function appendResource(tagname, url, async, defer, cb) {
    const tag = document.createElement(tagname);
    if (tagname === 'script') {
        tag.src = url;
        tag.async = async || false;
        tag.defer = async || defer || false;
    } else {
        return;
    }
    (document.head || document.documentElement).appendChild(tag);

    if (cb) {
        cb();
    }
}

Here is how we call the appendResource function:

const chartbeatSrc = '//static.chartbeat.com/js/chartbeat.js';
const callback = () => console.log('chartbeat script loaded');
appendResource('script', chartbeatSrc, '', true, callback);