Dynamically load JS and CSS files in JavaScript

Dynamically load JS and CSS files in JavaScript

From time to time, during your website development, you stumble upon this need, of loading JavaScript files or CSS files during runtime of a website.

I will share with you, not only the way of loading the script, but also make it complaint with the async-await methodology (using Promises).

The first function is called loadScript, it receives a URI as a parameter and creates a new script tag. This function returns a promise that will succeed when the script has been successfully loaded or fail on specified timeout (by default after 5 seconds).

/**
 * Dynamically loads JavaScript URI into the page.
 * @param {string} src The URI of the JavaScript file to load.
 * @param {DOMElement} appendToElement The element to append the script tag to. Default to `document.head`.
 * @param {number} timeoutMs Time in milliseconds indicates the timeout of the script loading. If the script isn't loaded in this time frame, the function will raise an error.
 * @returns {Promise} An instance of a Promise.
 * @author: Slavik Meltser <[email protected]>
 */
function loadScript(src, appendToElement = document.head, timeoutMs = 5000) {
    const script = document.createElement('script');
    script.setAttribute("type","text/javascript");
    script.setAttribute("src", src);
    const promise = new Promise((resolve, reject) => {
        let timeout = setTimeout(reject, timeoutMs, new Error(`Script load timed up (${src})`));
        script.onload = () => {
            clearTimeout(timeout);
            resolve();
        }
    });
    appendToElement.appendChild(script);
    return promise;
}

The second function is loadCSS. This function is simpler, as there is no need to trigger an event when the file is loaded, because, well, this is a CSS file. The function receives a URI as a parameter and appends a link element to DOM tree.

/**
 * Dynamycally loads StyleSheet URI into a page.
 * @param {string} href The StyleSheet file URI.
 * @param {DOMElement} appendToElement The element to append the 'link' tag to. Default to `document.head`.
 * @author: Slavik Meltser <[email protected]>
 */
function loadCSS(href, appendToElement = document.head) {
    var style = document.createElement("link");
    style.setAttribute("rel", "stylesheet");
    style.setAttribute("type", "text/css");
    style.setAttribute("href", href);
    appendToElement.appendChild(style);
}

Good luck!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.