为什么在 body 标签末尾有脚本 [英] Why scripts at the end of body tag
问题描述
我知道这个问题被问了很多次,但我还没有找到答案.那么为什么建议在 body 标签的末尾包含脚本以获得更好的渲染呢?
I know this question was asked many times, but I haven't found answer. So why its recommended to include scripts at the end of body tag for better rendering?
来自 Udacity course https://www.udacity.com/course/ud884 - 在 DOM 和 CSSOM 之后开始渲染准备好了.JS 是 HTML 解析阻塞,任何脚本都在 CSSOM 准备好后启动.
From Udacity course https://www.udacity.com/course/ud884 - rendering starts after DOM and CSSOM are ready. JS is HTML parse blocking and any script starts after CSSOM is ready.
所以如果我们得到:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>CRP</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- content -->
<script src="script.js"></script>
</body>
</html>
CRP 将是:
CSSOM ready > JS execute > DOM ready > Rendering
如果脚本在头:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>CRP</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<!-- content -->
</body>
</html>
CRP 是一样的:
CSSOM ready > JS execute > DOM ready > Rendering
这个问题仅与同步"脚本有关(没有 async/defer 属性).
This question is only about "sync" scripts (without async/defer attribute).
推荐答案
从历史上看,脚本会阻止其他资源更快地下载.通过将它们放在底部,您的风格、内容和媒体可以更快地下载,从而感知提高性能.
Scripts, historically, blocked additional resources from being downloaded more quickly. By placing them at the bottom, your style, content, and media could download more quickly giving the perception of improved performance.
Further reading: The async
and defer
attributes.
这篇关于为什么在 body 标签末尾有脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!