Loading scripts after page load?

后端 未结 7 1635
粉色の甜心
粉色の甜心 2020-11-27 15:16

I work with an advertising company, where we tag certain pages to track activity. A client of mine wants to fire off a javascript tag to track activity AFTER the page has fi

7条回答
  •  执念已碎
    2020-11-27 15:36

    For a Progressive Web App I wrote a script to easily load javascript files async on demand. Scripts are only loaded once. So you can call loadScript as often as you want for the same file. It wouldn't be loaded twice. This script requires JQuery to work.

    For example:

    loadScript("js/myscript.js").then(function(){
        // Do whatever you want to do after script load
    });
    

    or when used in an async function:

    await loadScript("js/myscript.js");
    // Do whatever you want to do after script load
    

    In your case you may execute this after document ready:

    $(document).ready(async function() {
        await loadScript("js/myscript.js");
        // Do whatever you want to do after script is ready
    });
    

    Function for loadScript:

    function loadScript(src) {
      return new Promise(function (resolve, reject) {
        if ($("script[src='" + src + "']").length === 0) {
            var script = document.createElement('script');
            script.onload = function () {
                resolve();
            };
            script.onerror = function () {
                reject();
            };
            script.src = src;
            document.body.appendChild(script);
        } else {
            resolve();
        }
    });
    }
    

    Benefit of this way:

    • It uses browser cache
    • You can load the script file when a user performs an action which needs the script instead loading it always.

提交回复
热议问题