近来对JS在html中的加载顺序有点小疑惑,遂测试分析了一把:
<html>
<head>
<div>before head</div>
<script type="text/javascript">
var test = function() {
alert("I'm in head!");
}
test();
</script>
<div>after head</div>
</head>
<body>
<script type="text/javascript">
var testPart1 = function() {
alert("I'm in body-part1!");
}
testPart1();
</script>
<div>Just a test case...</div>
<script type="text/javascript">
var testPart2 = function() {
alert("I'm in body-paer2!");
}
testPart2();
</script>
<script type="text/javascript">
var testPart3 = function() {
alert("I'm in body-part3!");
}
</script>
</body>
<script type="text/javascript">
var testEnd = function() {
alert("I'm in the end!");
}
testEnd();
</script>
<footer>you are in footer...<footer>
<script type="text/javascript">
alert("I'm behind of the footer!");
</script>
</html>
结果依次为:div标签"before head"出现,"I'm in head!",div标签"after head"出现,"I'm in body-part1!", div "Just a test case..."出现,"I'm in body-part2!","I'm in the end!",footer标签"
you are in footer..."出现,"I'm behind of the footer!"。
说明了以下几点:
1) 按照html从上到下的顺序加载(并不是都先加载head然后加载body,如果head放在body后,就变成了先加载body后加载head,只不过习惯上head在前)。
2) html的tags和script脚本也是按照位置的先后顺序加载的。
3) script中如果只有函数定义而没有去触发,这个函数是不会被执行的。