Categories

Asynchronous Loading of External Javascript

Posted on: June 11, 2014 by Dimitar Ivanov

Introduction

Loading of external javascript resources (libraries, plugins, widgets) should be done asynchronously, in a non-blocking manner, so the load time of your web-page will not be affected. Thus other resources like images and CSS are not blocked from loading.

HTML5 way

In the past that was possible with help of the defer attribute, later HTML5 spec introduce the async attribute.

<script src="//code.jquery.com/jquery-1.11.0.min.js" async>
</script>

Programatically way

Dynamically you can create script tag and inject it into the DOM.

<script type="text/javascript">
(function() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    script.src = "//code.jquery.com/jquery-1.11.0.min.js";
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
})();
</script>

You need a callback?

Often we need to know when the script is loaded, and when we are ready to use it. That's why we need a callback function. Also you can think about it as a dependency manager.

<script type="text/javascript">
function loadScript(url, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    if (script.readyState) {
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                if (callback && typeof callback === "function") {
                    callback();
                }
            }
        };
    } else {
        script.onload = function () {
            if (callback && typeof callback === "function") {
                callback();
            }
        };
    }
    script.src = url;
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
}
// How to use it
loadScript("//code.jquery.com/jquery-1.11.0.min.js", function () {
    // jQuery was loaded
    loadScript("//code.jquery.com/ui/1.10.4/jquery-ui.min.js");
});
</script>

ECMAScript 2017 (ES8) way

Callback functions runs the world of JavaScript before the advent of ECMAScript 2017 that standardized the use of async/await in conjunction with Promises (part of ECMAScript 2015).

<script type="text/javascript">
async function loadScripts (scripts) {
    
    function get (src) {
        return new Promise(function (resolve, reject) {
            var el = document.createElement("script");
            el.async = true;
            el.addEventListener("load", function () {
                resolve(src);
            }, false);
            el.addEventListener("error", function () {
                reject(src);
            }, false);
            el.src = src;
            (document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(el);
        });
    }

    const myPromises = scripts.map(async function (script, index) {
        return await get(script);
    });

    return await Promise.all(myPromises);
}

// How to use it
loadScripts([
    "https://static.zinoui.com/1.5/compiled/zino.svg.min.js",
    "https://static.zinoui.com/libs/jquery/jquery.min.js"
]).then(function () {
    return loadScripts(["https://static.zinoui.com/1.5/compiled/zino.chart.min.js"]);
}).then(function () {
    $("#chart").zinoChart(settings);
});
</script>
See also
Social sharing

If you have questions about async javascript loading, drop a comment below. And do not be shy to share this article. Thanks so much for reading!


1 Comment

raj
thanks for sharing this wonderful article.

I have an issue. I have a js code in ready on a master page that is executed in jquery's ajax post approach. The code is a webservice call. i mentioned async true in ajax options. So that when this script execution is happening, i want to continue my rest of the script execution.

Hence, when i load the default.aspx page, the ajax script on master page executes in async true fashion. and so i want to navigate to another page for some other work. However, the other page (lets say page2.aspx) is keep loading until the async code executes.

both pages inherits same master page.

could you please guide me where it is going wrong?

Comments are closed