把 JavaScript 放進頁面,最基本要處理的問題是「什麼時候執行」。若腳本在 DOM 尚未建立時就去抓元素,一定會拿到 null。以下兩種做法都能延後執行時機。
最直覺、相容性最好的方式,就是把 <script> 放到 </body> 之前。
<html> <head> <title>示例1</title> </head> <body> <!-- 頁面內容 --> <script type="text/javascript" src="example1.js"></script> <script type="text/javascript" src="example2.js"></script> </body> </html>
瀏覽器會依序下載並執行這兩個檔案,此時 DOM 已經準備好了。
為 <script> 加上 defer="defer",就能把腳本寫在 <head> 中,同時保證它在文件解析完成後才執行。
<html> <head> <title>示例1</title> <script type="text/javascript" defer="defer" src="example1.js"></script> <script type="text/javascript" defer="defer" src="example2.js"></script> </head> <body> <!-- 頁面內容 --> </body> </html>
這兩個屬性都只對外部檔案有效,行內腳本會被忽略。差別在於:
還有一個常見的替代做法:把初始化邏輯包在 DOMContentLoaded 事件監聽器中,這樣即使腳本放在 head 也能安全操作 DOM。