我知道这个问题被问了很多次,但我没有找到答案。那么为什么建议将脚本包含在body标签的末尾以实现更好的渲染?
来自Udacity课程https://www.udacity.com/course/ud884 - 渲染开始于DOM和CSSOM准备就绪之后。JS是HTML解析阻塞并且任何脚本都要在CSSOM准备就绪之后开始运行。
所以如果我们有:
<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
如果脚本位于 head 中:
<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属性)。