我有一个很大的 JavaScript 文件要在网页加载期间使用。我希望它可以尽早下载(下载不会阻止 UI 线程),但不会立即评估(将其加载到内存中是在 UI 线程中,并阻止 domcontentcomplete 事件,从而阻止初始页面绘制)。
它将初始化 XHR 以获取附加数据并更新页面。用户会较早看到静态页面并稍后获得所有数据。如果是在html head中,则初始静态页面显示会延迟。如果在页尾,下载会延迟整个内容的显示。
有没有办法下载但不解析,直到我稍后启动解析?
最佳答案
如果 JS 文件对渲染并不重要,您可以使用 async
或defer
<script>
上的属性文件的标签。使用async
基本上与放置 <script>
具有相同的效果结束前的标签 <body>
标签。
async
HTML5 Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously. It has no effect on inline scripts (i.e., scripts that don't have the src attribute).
defer
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred.
您也可以使用setTimeout
称呼。只要<script>
不会阻止任何渲染,将其包装在 setTimeout
中应该为你延迟一下。
var delay = 10 /* or however many ms you want */
setTimeout(function(){
/* your code goes here */
}, delay)
编辑:如果您希望在 DomContentLoaded
之后专门执行事件,只需将代码包装在该事件的事件监听器中。
document.addEventListener("DOMContentLoaded", function(event) {
/* Your code goes here */
});
关于javascript - 下载 javascript 文件但不立即评估它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29379125/