为什么script标签一般放在body下面

https://www.jianshu.com/p/86250c123e53

通常我们在开发html时,通常将script标签放到body标签下面,那原因到底是为什么呢?

js代码在载入完后,是立即执行的。

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var item = document.getElementById("item");
console.log(item); //null
</script>
</head>

<body>
<div id="item">
我是html结构,我要展示到页面上!
</div>
</body>

</html>

通过这个简单的例子我们可以看到,js代码在加载完后,是立即执行的,执行完后,body才开始解析渲染,所以是找不到item,所以为null。

js代码执行时会阻塞页面渲染(由于GUI渲染线程和js引擎线程互斥。具体原理可以看这)

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
while (true) {
console.log(1);
}
</script>
</head>

<body>
<div id="item">
我是html结构,我要展示到页面上!
</div>
</body>

</html>

测试结果,浏览器一直处于加载过程,一会就卡死了。html整个结构(包括html标签)都无法渲染出来。js的下载和执行会阻塞Dom树的构建。

1523429832(1).jpg

所以,我们一般采用以下方法

  • 将所有的script标签放到页面底部,也就是body闭合标签之前,这能确保在脚本执行前页面已经完成了DOM树渲染。

如果放在上面,将js包裹在$(document).ready(function(){})或者$(function(){})里面
,或者window.onload=function(){}里面。

具体这几句代码什么意思,可以看一下文章
ready和onload的区别

原文地址:https://www.cnblogs.com/sunny3158/p/15087201.html