javascript - 下载 javascript 文件但不立即评估它?

标签 javascript performance page-load-time

我有一个很大的 JavaScript 文件要在网页加载期间使用。我希望它可以尽早下载(下载不会阻止 UI 线程),但不会立即评估(将其加载到内存中是在 UI 线程中,并阻止 domcontentcomplete 事件,从而阻止初始页面绘制)。

它将初始化 XHR 以获取附加数据并更新页面。用户会较早看到静态页面并稍后获得所有数据。如果是在html head中,则初始静态页面显示会延迟。如果在页尾,下载会延迟整个内容的显示。

有没有办法下载但不解析,直到我稍后启动解析?

最佳答案

如果 JS 文件对渲染并不重要,您可以使用 asyncdefer <script> 上的属性文件的标签。使用async基本上与放置 <script> 具有相同的效果结束前的标签 <body>标签。

< Script > - MDN

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/

相关文章:

PHP 通知 : A non well formed numeric value encountered

javascript - 如何切换任何表单输入(不是一次全部)?

javascript - Laravel:通过 min.js 文件 "Uncaught ReferenceError: HelloWeek is not defined"包含 javascript 代码

c - 如何确定内联汇编在何处/针对什么可以提供更高的执行速度?

javascript - 我们如何防止 OpenX 阻塞页面加载?

Angular 性能跟踪

javascript变量包含而不是等于

php - AJAX/JAVASCRIPT 投票 mysql

c++ - C/C++ 中最快/最短的方法来计算二进制数字之和/又称二进制中 1 的数量

ios - PDFKit - 使用 pageViewController 的 PDFView - 滑动到下一页时页面呈现缓慢