javascript写在head和body里的区别
页面加载的时候是从上往下执行的,即先执行<head>再执行<body>。
Javascript写在哪里?概括起来就是三种形式:
1. 内部:Html网页的<head></head>中;
2. 内部:Html网页的<body></body>中;
3. 外部:外部JS文件里。
1. 内部:Html网页的<head></head>中:
js在head里时,由于页面加载循序的原因,不需要首次加载的js建议放入head中。如果你将首次执行的代码放入head中,会出现DOM还未被页面渲染,js无法执行的尴尬,例如下面:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<
doctype
html
>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>
js加载顺序
<
/
title
>
<script
type
=
"text/javascript"
>
var
today
=
new
Date
(
)
;
document
.
getElementById
(
"timer"
)
.
innerHTML
=
"<h2>"
+
today
+
"</h2>"
;
</script>
<
/
head
>
<
body
>
<
div
id
=
"timer"
>
<
/
div
>
<
/
body
>
<
/
html
>
|
页面是空白的。 但是你可以在这点代码的body中加入 onLoad=”load()“ 来弥补:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<
doctype
html
>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>
js加载顺序
<
/
title
>
<script
type
=
"text/javascript"
>
function
load
(
)
{
var
today
=
new
Date
(
)
;
document
.
getElementById
(
"timer"
)
.
innerHTML
=
"<h2>"
+
today
+
"</h2>"
;
}
</script>
<
/
head
>
<
body
onLoad
=
"load()"
>
<
div
id
=
"timer"
>
<
/
div
>
<
/
body
>
<
/
html
>
|
onload 事件会在页面或图像加载完成后立即发生。所有这个事件调用load()方法致使js再次调用渲染完成的html的DOM元素
2. 内部:Html网页的<body></body>中;
当浏览器载入网页Body部分的时候,就执行其中的Javascript语句,执行之后输出的内容就显示在网页中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<
doctype
html
>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>
js加载顺序
<
/
title
>
<
/
head
>
<
body
>
<
div
id
=
"timer"
>
<
/
div
>
<script
type
=
"text/javascript"
>
var
today
=
new
Date
(
)
;
document
.
getElementById
(
"timer"
)
.
innerHTML
=
"<h2>"
+
today
+
"</h2>"
;
</script>
<
/
body
>
<
/
html
>
|
之前未运行的代码现在正常了。
3. 外部:外部JS文件里。
也就是说我们把相应的代码整理到一个独立的js文件中,使其能够被重用并让html页面更加简洁干净:
例如
1
|
<script
src
=
"js/test.js"
>
</script>
|
总结:在head中加入的代码如果需要和DOM打交道那么可能会报错,所以一般将JS代码加在body的最后,这样当执行这行代码的时候所的DOM都已经载入完成了。