简体   繁体   English

推迟js的有效方法

[英]Efficient way to defer js

I intend to call a js, which will not use anything when loading the page.我打算调用一个js,它在加载页面时不会使用任何东西。 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.因此,我只需要在整个页面加载完毕后调用这个js,以免耽误任何事情或为用户加载屏幕。

<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. “defer”关键字延迟脚本的加载,直到触发 DOMContentLoaded 事件。

From the Mozilla Developer Center :来自Mozilla 开发者中心

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). DOMContentLoaded 事件在文档完全加载和解析后触发,无需等待样式表、图像和子框架完成加载(加载事件可用于检测完全加载的页面)。

This means that version 1 (defer) will possibly start loading the scripts earlier than version 2, while still keeping the loading efficient.这意味着版本 1(延迟)可能会比版本 2 更早地开始加载脚本,同时仍保持加载效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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