1,在head中時,所代表的functions只加載而不執行,執行是在某一事件觸發後纔開始。
2,在body中時,直接加載並執行
典型的區別:
如果有不在函數中的執行語句,比如變量初始化,如果在head中就不會執行。
例如:
- <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>
- <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中,變量初始化需要另外想辦法