how to load external javascript asynchronously

There are ways of loading of external javascript asynchronously.

  1. use HTML5 with async attribute

<script src="//code.jquery.com/jquery-1.11.0.min.js" async></script>
  1. Dynamically create script tag and inject it into the DOM.

(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);
})();
  1. call a callback function when loading finish

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");
});
  1. use async/await with Promises In ES8

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([
    "//code.jquery.com/jquery-1.11.0.min.js"
]).then(function () {
    return loadScripts(["//code.jquery.com/ui/1.10.4/jquery-ui.min.js"]);
}).then(function () {
    $("#chart").set(options);
});


date2019-04-16 11:43:38 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

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