JavaScript代碼放置的位置

來源:互聯網
上載者:User

1. 放在head中
這種方式會在頁面載人前載入js代碼,這樣的話,我們不能在head中取得網頁元素,因為網頁還沒載入,看下面的例子,當我們要動態修改按鈕顯示的值的時候,在head中的代碼就會報一個Cannot
 set property 'value' of null的錯。這個錯誤時在chrome中調試得出的,在IE中也會報一個'document.getElementById(...)' 為空白或不是對象的錯誤。當然,如果你把js代碼放到body中就沒問題了。
[html] 
<html> 
<head> 
<script type="text/javascript"> 
document.getElementById('click_button').value = '點擊我!'; 
function show_message(){ 
    alert('Hello!'); 

</script> 
</head> 
<body> 
<input id="click_button" type="button" value="Click me!" onclick="show_message()" > 
<script type="text/javascript"> 
document.getElementById('click_button').value = '點擊我!'; 
</script> 
</body> 
</html> 

 

2. 放在body中
根據放置的位置順序執行js指令碼。比如上面的例子,如果我們把js放到元素載入前,也會報錯的。
[html] 
<html> 
<head> 
</head> 
<body> 
<script type="text/javascript"> 
document.getElementById('click_button').value = '點擊我!'; 
</script> 
<input id="click_button" type="button" value="Click me!" onclick="show_message()" > 
</body> 
</html>   www.2cto.com

 

提示:當js檔案比較大的時候,建議在</body>前的位置載入js檔案,這樣不會影響網頁的載入速度,如果放在頭部的話,會先載入js檔案。


作者:lixiang0522

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.