JavaScript 代碼可在 HTML 文檔的多個位置嵌入,每種方式有不同的加載時機與適用場景。本文系統梳理四種主流插入方式及外部文件引用最佳實踐。
<html>
<head>
<script type="text/javascript">
function sayHello() { alert('Hello World'); }
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
優點: 函數定義預先加載,事件調用不會報錯。缺點: 阻塞頁面渲染。
<body>
<script type="text/javascript">
document.write('Hello World'); // 頁面加載時直接輸出內容
</script>
<p>This is web page body</p>
</body>
適用: 需在文檔流中輸出內容的腳本。
<head>
<script> function sayHello() { alert('Hello World'); } </script>
</head>
<body>
<script> document.write('Hello World'); </script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
場景: 函數定義在 head,即時執行代碼在 body。
<head>
<script type="text/javascript" src="filename.js"></script>
</head>
優勢:
filename.js 內容:
function sayHello() { alert('Hello World'); }
</body> 前(或使用 defer/async 屬性)