Asynchronous Loading of External Javascript

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 thedefer 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>
Asynchronous Loading of External Javascript Written By Dimitar Ivanov On Asynchronous Loading of External Javascript. Posted on: June 11, 2014

Comments

Popular posts from this blog

How to Make Blogger Safelink Converter v3

List of weapon buff materials, effects and how it can be durango wild lands

Install deb package via Termux