简体   繁体   中英

Efficient way to defer js

I intend to call a js, which will not use anything when loading the page. Therefore, I need to call this js only when the entire page has been loaded, so as not to delay anything or load the screen for the user.

<html>
    <body>
    <script type="text/javascript" defer=defer src="function.js"></script>
    <script type="text/javascript">
            function downloadJSAtOnload() {
                var element = document.createElement("script");
                element.src = "function.js";
                document.body.appendChild(element);
            }       
            if (window.addEventListener)
                window.addEventListener("load", downloadJSAtOnload, false);
            else if (window.attachEvent)
                window.attachEvent("onload", downloadJSAtOnload);
            else window.onload = downloadJSAtOnload;
    </script> 
    </body>
    </html>

My question is: in the above ways, which one would be more efficient? I need to decrease the loading time of my page and with that I want to "postpone" everything that is not necessary.

The “defer” keyword postpones loading of scripts until the DOMContentLoaded event is fired.

From the Mozilla Developer Center :

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

This means that version 1 (defer) will possibly start loading the scripts earlier than version 2, while still keeping the loading efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM