HTML 文件由「頭部」與「主體」兩大區塊組成,分工明確:<head> 提供瀏覽器解析所需的中繼資料,<body> 裝載使用者實際看到的內容。深入理解兩者差異,是撰寫標準、高效能網頁的關鍵。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<!-- 中繼資料區:不直接顯示在畫面 -->
<meta charset="UTF-8">
<title>頁面標題</title>
<meta name="description" content="頁面描述">
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
</head>
<body>
<!-- 可見內容區:使用者互動的所有元素 -->
<header>...</header>
<main>...</main>
<footer>...</footer>
</body>
</html>
| 元素 | 用途 | 必要性 | 範例 |
|---|---|---|---|
| <title> | 瀏覽器分頁標題、書籤名稱、SEO 標題 | 必填 | <title>產品介紹</title> |
| <meta charset> | 宣告字元編碼 | 必填 | <meta charset="UTF-8"> |
| <meta name="viewport"> | 響應式視口設定 | 行動裝置必填 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| <meta name="description"> | 搜尋結果摘要描述 | SEO 強烈建議 | <meta name="description" content="..."> |
| <link> | 引入外部資源(CSS、圖示、預載) | 常用 | <link rel="stylesheet" href="main.css"> |
| <style> | 內嵌 CSS 樣式 | 偶用 | <style>body{font-family:sans-serif}</style> |
| <script> | 載入或內嵌 JavaScript | 常用 | <script src="app.js" defer></script> |
| <base> | 指定相對連結基準 URL | 少用 | <base href="https://example.com/"> |
| <noscript> | JS 停用時的替代內容 | 漸進增強 | <noscript>請啟用 JS</noscript> |
<body> 內容即使用者可見、可互動的一切:
<header>, <nav>, <main>, <section>, <article>, <aside>, <footer><h1-h6>, <p>, <ul>, <ol>, <blockquote>, <pre><img>, <video>, <audio>, <picture>, <canvas>, <svg><form>, <input>, <button>, <select>, <textarea>, <dialog><table>, <thead>, <tbody>, <tfoot>, <tr>, <th>, <td><style> 或 <script> 放在 <body> 結尾<head>,JS 加 defer 放 <head> 或 <body> 末尾。<title> 放在 <body><title> 僅能出現在 <head>,否則無效。<head> 或 <body><meta charset> 應盡早出現<head> 第一行,確保瀏覽器以正確編碼解析後續內容。<style> 內嵌,其餘非關鍵 CSS 用 media="print" onload="this.media='all'" 非同步載入。<script src="..." defer>(依序執行)或 async(獨立執行),避免阻塞 DOM 建構。<link rel="preconnect" href="https://fonts.gstatic.com">, <link rel="preload" as="font" href="font.woff2" type="font/woff2" crossorigin>。<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://cdn.example.com"> 防禦 XSS。釐清 <head> 與 <body> 的職責邊界,不只能寫出合規格的 HTML,更能從架構層面優化載入效能、SEO 與安全性。下次撰寫網頁時,試著問自己:「這個標籤是給瀏覽器看的中繼資料,還是給使用者看的內容?」