javascript - 在结束的 body 标签的末尾添加 defer 到脚本标签是多余的吗?

标签 javascript html

例如:

<body>
  ...all content is above the script...
  <script src="https://foo/bar.js" defer></script>
</body>

如果我们从脚本标签中删除 defer 有关系吗?将脚本放在 body 标签的末尾已经延迟了脚本的执行,所以上面的代码应该与下面的代码片段相同,对吗?

<body>
  ...all content is above the script...
  <script src="https://foo/bar.js"></script>
</body>

最佳答案

根据 Ben

The current best practice? Use deferred scripts in order in the head, unless you need to support older browsers (IE < 10, Opera Mini, etc.) - 97.45% browser usage (ref)

Why? With defer, parsing finishes just like when we put the script at the end of the body tag, but overall the script execution finishes well before, because the script has been downloaded in parallel with the HTML parsing. This scenario will trigger the faster domInteractive event that is used for page loading speed. With async, the order in which your script will execute varies based on how fast the script is fetched, so order can be compromised. Futhermore, async scripts are executed inline and pause the parsing of the HTML.

同样来自 Mhmdrz_A

Browser will parse the document from top to bottom, hence putting the scripts after all the main content will make the parser to reach that

later in time; which make the browser to download the script later in time; The delay caused by putting the defer in the bottom is absolutely non-sense, since the browser won't execute them (s) before (or during) HTML parser; Thus it's better to let the browser load ( download ) them () as soon as possible, an have them available to execute as soon as the all the main tasks are done.

关于javascript - 在结束的 body 标签的末尾添加 defer 到脚本标签是多余的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72525045/

相关文章:

javascript - 为什么 UnderscoreJS 有很多原生 Javascript 函数的包装函数?

javascript - 如何将我的数据转换成适合 d3.js sunburst 的格式?

html - 如何在 html 中嵌入 wave 文件(跨平台)

html - 表中一行三个元素

javascript - Rails 在 html 公共(public)文件中包含 js

javascript - 切换 Font Awesome 不起作用

javascript - menucool 工具提示 javascript 购买弹出窗口

javascript - 如何获取 HTML 元素的原始高度?

html - 移动 HTML Canvas 元素的 "camera"

javascript - JQuery/JavaScript : Enable and disable div