js script放在head跟body里面的区别
js script放在head和body里面的区别? ??java script放在head和body的区别?1,在head中时,所代表的functions
js script放在head和body里面的区别
? ??java script放在head和body的区别?
1,在head中时,所代表的functions只加载而不执行,执行是在某一事件触发后才开始。 2,在body中时,直接加载并执行
典型的区别:
如果有不在函数中的执行语句,比如变量初始化,如果在head中就不会执行。
例如:
[html] view plaincopy?
- <html>??
- ????<head>??
- ????<title>第一个Html5视频测试</title>??
- ????????<script?type="text/javascript">??
- ????????????var?myVideo=document.getElementById("video1");??
- ??????????????
- ????????????function?playPause()??
- ????????????{???
- ????????????????if?(myVideo.paused)???
- ??????????????????myVideo.play();???
- ????????????????else???
- ??????????????????myVideo.pause();???
- ????????????}???
- ????????</script>???
- ????</head>??
- ????<body>??
- ????????<div?style="text-align:center;">??
- ????????????<button?onclick="playPause()">播放/暂停</button>???
- ????????????<br/>???
- ????????????<video?id="video1"?src="mov_bbb.ogg"?width="320"?height="240"?controls="controls">??
- ????????????????Your?browser?does?not?support?the?video?tag.??
- ????????????</video>??
- ????????</div>??
- ????</body>??
- </html>??
点击“播放/暂停”时,playPause会被执行,但执行时myVideo对象没有定义的,因为定义和初始化语句被有执行过。
如果要执行,需要放在body
[html] view plaincopy?
- <html>??
- ????<head>??
- ????<title>第一个Html5视频测试</title>??
- ????</head>??
- ????<body>??
- ????????<div?style="text-align:center;">??
- ????????????<button?onclick="playPause()">播放/暂停</button>???
- ????????????<br/>???
- ????????????<video?id="video1"?src="mov_bbb.ogg"?width="320"?height="240"?controls="controls">??
- ????????????????Your?browser?does?not?support?the?video?tag.??
- ????????????</video>??
- ????????</div>??
- ????????<script?type="text/javascript">??
- ????????????var?myVideo=document.getElementById("video1");??
- ??????????????
- ????????????function?playPause()??
- ????????????{???
- ????????????????alert("AA");??
- ????????????????if?(myVideo.paused)???
- ??????????????????myVideo.play();???
- ????????????????else???
- ??????????????????myVideo.pause();???
- ????????????}???
- ????????</script>???
- ????</body>??
- </html>??
当然,javascript放在head中有其他的好处的,所以,如果必须放在head中,变量初始化需要另外想办法