浏览器是从上到下依次加载并解析的。
当浏览器加载html文件并解析到时,页面也就是并没有被解析,浏览器会等到中的js执行完再加载页面。
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
console.log('this is head js ');
</script>
<script type="text/javascript" src='test.js'></script>
<style type="text/css">
body{
color: red;
}
</style>
</head>
<body>
<script type="text/javascript">
console.log('this is body js');
window.onload=function(){
console.log('this is onload js');
};
</script>
<p >this is body</p>
</body>
</html>
输出:
this is head js
this is test js
this is body js
this is onload js
由此可见head和头部引进的script脚本最先加载并执行,而onload是最后执行的,所以处于<body>和</body>
中的元素是在页面加载的时候被执行的。
了解这个有什么用呢?
假如说你把DOM操作放在了<head>
标签里,你会发现报错,这是因为DOM树还没建立,getElementById获取的是undefined。
所以说最好把<script>
放在<body></body>
的尾巴,除非一些外部的库需要调用可以放head前面,这样会提前加载,就不会在加载页面时再加载外部库而造成延迟。