DIV CSS 佈局教程網

如何引入(呼叫)外部 JS 檔案
編輯:關於JavaScript     

開發時我們常常需要把 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>

寫法二:抽到外部檔案 a.js

把 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 與 async:把 script 放在 head 時,加上 defer 可讓它在 DOM 解析完才執行,避免取不到元素;async 則是載完即執行,順序不保證。
  • setInterval 盡量傳函式而非字串。寫成 setInterval(count, 100) 比 setInterval("count();", 100) 好,後者相當於 eval,效能與安全性都較差。
  • 避免污染全域。範例中的 max 與 timeId 漏了 var 會變成全域變數,容易與其他腳本衝突。
  • 搭配 defer 或 module。現代專案建議直接用 ES Module 的 import/export,或把 script 標籤寫成 type="module",天然擁有作用域隔離。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved