当前位置: 代码迷 >> JavaScript >> js script放在head跟body里面的区别
  详细解决方案

js script放在head跟body里面的区别

热度:3993   发布时间:2014-02-21 00:12:52.0
js script放在head和body里面的区别
? ??java script放在head和body的区别
?
  1,在head中时,所代表的functions只加载而不执行,执行是在某一事件触发后才开始。
  2,在body中时,直接加载并执行

典型的区别:
如果有不在函数中的执行语句,比如变量初始化,如果在head中就不会执行。

例如:
[html] view plaincopy
?
  1. <html>??
  2. ????<head>??
  3. ????<title>第一个Html5视频测试</title>??
  4. ????????<script?type="text/javascript">??
  5. ????????????var?myVideo=document.getElementById("video1");??
  6. ??????????????
  7. ????????????function?playPause()??
  8. ????????????{???
  9. ????????????????if?(myVideo.paused)???
  10. ??????????????????myVideo.play();???
  11. ????????????????else???
  12. ??????????????????myVideo.pause();???
  13. ????????????}???
  14. ????????</script>???
  15. ????</head>??
  16. ????<body>??
  17. ????????<div?style="text-align:center;">??
  18. ????????????<button?onclick="playPause()">播放/暂停</button>???
  19. ????????????<br/>???
  20. ????????????<video?id="video1"?src="mov_bbb.ogg"?width="320"?height="240"?controls="controls">??
  21. ????????????????Your?browser?does?not?support?the?video?tag.??
  22. ????????????</video>??
  23. ????????</div>??
  24. ????</body>??
  25. </html>??
点击“播放/暂停”时,playPause会被执行,但执行时myVideo对象没有定义的,因为定义和初始化语句被有执行过。
如果要执行,需要放在body
[html] view plaincopy
?
  1. <html>??
  2. ????<head>??
  3. ????<title>第一个Html5视频测试</title>??
  4. ????</head>??
  5. ????<body>??
  6. ????????<div?style="text-align:center;">??
  7. ????????????<button?onclick="playPause()">播放/暂停</button>???
  8. ????????????<br/>???
  9. ????????????<video?id="video1"?src="mov_bbb.ogg"?width="320"?height="240"?controls="controls">??
  10. ????????????????Your?browser?does?not?support?the?video?tag.??
  11. ????????????</video>??
  12. ????????</div>??
  13. ????????<script?type="text/javascript">??
  14. ????????????var?myVideo=document.getElementById("video1");??
  15. ??????????????
  16. ????????????function?playPause()??
  17. ????????????{???
  18. ????????????????alert("AA");??
  19. ????????????????if?(myVideo.paused)???
  20. ??????????????????myVideo.play();???
  21. ????????????????else???
  22. ??????????????????myVideo.pause();???
  23. ????????????}???
  24. ????????</script>???
  25. ????</body>??
  26. </html>??
当然,javascript放在head中有其他的好处的,所以,如果必须放在head中,变量初始化需要另外想办法
  相关解决方案