## 外部
第一種也是推薦的方式是在一個外部文件(帶有?`.js`?擴展名)編寫代碼,然后可以使用 HTML?`script`?元素并通過?`src`?屬性指定文件的位置來引入到網頁中。當你需要將代碼重復使用在其他頁面時,保持 JavaScript 在一個單獨的文件中可以減少代碼的重復。另外它也可以讓瀏覽器將文件緩存到客戶端的計算機上,減少網頁加載時間。
~~~
<!-- Code is written in a .js file, included via the script tag src attribute. -->
<script src="/path/to/example.js"></script>
~~~
## 內嵌
第二種方式是直接將代碼內嵌在網頁中。它也是通過 HTML?`script`?元素實現,但不是通過?`src`?屬性指定一個文件,而是將代碼放置在元素中間。雖然有些情況下可以使用這種方式,但大部分時間,最好是如上所述將我們的代碼放置在外部文件中。
~~~
<!-- Embed code directly on a web page using script tags. -->
<script>
alert( "Hello World!" );
</script>
~~~
## 屬性
最后一個選擇是使用 HTML 元素的事件處理程序屬性。這種方式是強烈不推薦的:
~~~
<!-- Inline code directly on HTML elements being clicked. -->
<a href="javascript:alert( 'Hello World' );">Click Me!</a>
<button onclick="alert( 'Good Bye World' );">Click Me Too!</button>
~~~
## 位置
在上面的前兩個方式中,代碼的位置是重要的,并且需要根據情況而改變。如果你添加不訪問頁面元素的 JavaScript,你可以放心的把腳本放在 HTML?`</head>`之前。但是,如果代碼將與頁面上的元素交互,就必須確保在執行代碼時這些元素已經存在了。可以在下面的例子中看到這個常見的陷阱,一段查找 ID 為`hello-world`?的元素腳本將會在頁面定義元素之前執行。
~~~
<!doctype html>
<html>
<head>
<script>
// Attempting to access an element too early will have unexpected results.
var title = document.getElementById( "hello-world" );
console.log( title );
</script>
</head>
<body>
<h1 id="hello-world">Hello World</h1>
</body>
</html>
~~~
一個常見的模式是將腳本移動到頁面的底部,HTML?`</body>`?前。這可以保證當執行代碼時,元素已經在頁面中定義了:
~~~
<!doctype html>
<html>
<head></head>
<body>
<h1 id="hello-world">Hello World</h1>
<script>
// Moving the script to the bottom of the page will make sure the element exists.
var title = document.getElementById( "hello-world" );
console.log( title );
</script>
</body>
</html>
~~~