例如:
<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/