<head> <script> // JavaScript code here </script> <title>Script in Head</title> </head> <h1>Hello, World!</h1>
執行過程:
<script>
中遇到 <head>
標籤時,HTML 渲染會在腳本下載和執行時暫停。 缺點:
理想用例:
2。 <script>
標籤位於 <body>
<title>Script at Bottom</title> <h1>Hello, World!</h1> <script> // JavaScript code here </script>
執行過程:
<script>
末尾的<body>
標籤在頁面渲染後處理並執行。 優點:
缺點:
理想用例:
3。 <script>
帶有 async
屬性的標籤
<head> <script async src="script.js"></script> <title>Script with Async</title> </head> <h1>Hello, World!</h1>
執行過程:
async
腳本時,它會在繼續 HTML 載入的同時同時下載腳本。 優點:
缺點:
async
腳本,腳本可能會以不可預測的順序執行。 理想用例:
4。 <script>
帶有 defer
屬性的標籤
<head> <script> // JavaScript code here </script> <title>Script in Head</title> </head> <h1>Hello, World!</h1>
執行過程:
defer
腳本與 HTML 同時下載,但僅在解析整個 HTML 後才執行。 DOMContentLoaded
事件之前。 優點:
defer
腳本,則保持腳本執行順序。 理想用例:
比較表
<表> <標題>Method | Execution Time | Blocks Rendering | Best Use Case |
---|---|---|---|
<script> in <head> |
Before HTML load | Yes | Configuration, early execution logic |
<script> at end of <body> |
After HTML load | No | DOM manipulation, event handling |
<script async> |
When script is downloaded | No (except during execution) | Analytics, ads, independent scripts |
<script defer> |
After HTML parse | No | DOM-dependent scripts |
<腳本延遲>
<script>
<body>
<script async>
末尾使用 <body>
將 <head>
如果沒有使用任何屬性,請將腳本放在 async
的底部,以實現頁面平滑載入。 defer
的 <script>
中,除非絕對有必要防止渲染阻塞。
以上是在 HTML 中使用