開發時我們常常需要把 JavaScript 抽到獨立檔案再引入頁面,這樣不但好維護,也能讓瀏覽器快取。以下用一個「隨機抽取人名」的小例子,示範同一份邏輯在內嵌與外部檔案兩種寫法下的差異。
<html> <head> <title>random number</title> <script type="text/javascript"> // 隨機抽取人名 </script> </head> <body> <form> <input type="button" style='font-size:40px' value="Start" onclick="start()"> <input type="button" style='font-size:40px' value="Stop" onclick="stop();"> </form> <br> <font color="blue" style='font-size:150px' id="num"></font> </body> </html>
把 JavaScript 移到同一個資料夾下的 a.js,HTML 只要用 src 指向它,script 標籤本身留空即可:
<html> <head> <title>random number</title> <script type="text/javascript" src="a.js"></script> </head> <body> <form> <input type="button" style='font-size:40px' value="Start" onclick="start()"> <input type="button" style='font-size:40px' value="Stop" onclick="stop();"> </form> <br> <font color="blue" style='font-size:150px' id="num"></font> </body> </html>
外部檔案的內容:
var errorString = "Please input a positive integer.";
var arr = ["A", "B", "C", "D"];
function count() {
max = arr.length; // 全域變數
document.getElementById("num").innerHTML = arr[parseInt(max * Math.random())];
}
function start() {
timeId = setInterval("count();", 100);
}
function stop() {
clearInterval(timeId);
}
若 JS 部署在網站或 CDN 上,用絕對路徑引入即可:
<script type="text/javascript" src="https://localhost:8080/test/js/random1.js"></script>
defer 可讓它在 DOM 解析完才執行,避免取不到元素;async 則是載完即執行,順序不保證。setInterval(count, 100) 比 setInterval("count();", 100) 好,後者相當於 eval,效能與安全性都較差。max 與 timeId 漏了 var 會變成全域變數,容易與其他腳本衝突。import/export,或把 script 標籤寫成 type="module",天然擁有作用域隔離。