1. 什麼是 Modern Web Guidance?
Modern Web Guidance 會直接將現代化最佳做法和瀏覽器相容性套用至您的程式碼編寫代理。這些技能可確保您的程式碼與目前的網路平台功能保持一致。無論是開發新原型或重構舊版系統,Modern Web Guidance都能提供現代網路標準的存取權。
開發人員可使用這項工具執行下列操作:
- 穩紮穩打:開始使用可互通的網頁功能開發專案。
- 更新舊版程式碼:取代常見使用者介面模式的自訂實作項目。
- 在開發過程中學習:這項技能會在開發期間提供情境感知指引,協助您增進對現代網路模式的瞭解。
稽核舊版應用程式、設定 Baseline 目標,並根據 Modern Web Guidance 規則對比標準 AI 建議,您就能學會提示 Modern Web Guidance 強化編碼代理程式,產生高效能的現代網路程式碼,而不是依賴過時或一般模型輸出內容。
2. 必要條件
開始本程式碼研究室之前,請先確認您已具備下列知識:
- Modern Web Guidance 說明文件和與代理程式無關的安裝方式
- 對 Baseline 和 Lighthouse 有基本瞭解
- 瞭解提示的基本概念
本程式碼研究室使用下列項目:
- Modern Web Guidance (v0.0.173)
- Antigravity CLI (搭載 Gemini 3.5 Flash 的 v1.0.10)
本程式碼研究室會從舊版「Cozy Nook」應用程式開始,該應用程式刻意由舊版程式碼組成。複製示範存放區,然後前往 cozy-nook-bookshop 網頁應用程式。
git clone git@github.com:GoogleChromeLabs.modern-web-guidance-demos.git
cd modern-web-guidance-demos/legacy-demos/cozy-nook-bookshop/
3. 設定基準目標
基準提供資訊,說明目前瀏覽器可互通運作的功能。此外,您也可以透過這項功能指定要支援的瀏覽器,不必指定瀏覽器引擎和版本。如果某項功能可互通,就會視為「基準」。
開發網頁應用程式前,請先選擇 Baseline 目標。根據預設,modern-web-guidance 會使用「Baseline Widely available」,其中包含互通性至少達 30 個月的功能。如要支援新版功能,您必須在 AGENTS.md 檔案中加入適當的 Baseline 目標。
在本程式碼研究室中,這個專案會使用 baseline widely available on 2026-06-01 的固定目標。
// AGENTS.md
This project's Baseline target is "Baseline widely available on 2026-06-01".
4. 判斷專案優先順序
選擇基準目標後,請定義優先順序,並將相關功能和主題分批處理。採用漸進式改善的思考模式,就像建構功能時一樣。
根據特定過時功能或更廣泛的網頁開發領域,將更新分類,例如:
- 效能:最佳化Core Web Vitals。
- 使用者體驗:改善互動和可用性。
- 無障礙功能:解決無障礙功能問題,讓更多人可以使用您的應用程式。
- 表單和安全性:更新輸入處理方式,並強化應用程式的資料輸入點。
在本程式碼研究室中,您將著重比較舊版書店應用程式的效能,瞭解 Modern Web Guidance 技能如何提升速度。一次專注於一項工作,監控代理執行的變更,確保結果符合專案目標。
首先,請使用 Lighthouse 稽核,清楚瞭解 bookshop 應用程式在初始狀態下的效能。
在本機開啟 Antigravity CLI,然後啟動新的工作階段:
agy
您應該會看到類似以下的代理程式輸出內容。
● Bash(ctrl+o to expand)
▸ Thought for 13s
This report will detail the desktop and mobile scores, provide a comparative metrics table, explain the root causes of the performance bottlenecks, and offer highly actionable recommendations based on modern web standards (e.g. Baseline Widely available on 2026-06-01 target).
● Create(lighthouse_audit_report.md) (ctrl+o to expand)
▸ Thought for 5s
Confirming Task Completion
I have successfully run the Lighthouse audits using npx lighthouse for both desktop and mobile viewports against a production build of the application.
The generated local reports have been saved in the project root:
• Mobile Reports: lighthouse-mobile.report.html and lighthouse-mobile.report.json
• Desktop Reports: lighthouse-desktop.report.html and lighthouse-desktop.report.json
I have compiled the audit scores, identified performance bottlenecks, and outlined a step-by-step key improvement action plan in the following artifact:
Open lighthouse_audit_report.md
開啟 Markdown 後,我們會得到下列結果:
Here is the complete Lighthouse audit report generated for the application:
**Lighthouse Audit Report: Cozy Nook Bookshop**
This report provides the Lighthouse audit scores, core web vitals performance
metrics, and key areas for improvement for The Legacy Cozy Nook in development mode.
**Summary Scores**
| Category | Mobile Score | Desktop Score |
|-----------------|--------------|---------------|
| Performance | 61 / 100 | 93 / 100 |
| Accessibility | 98 / 100 | 98 / 100 |
| Best Practices | 96 / 100 | 96 / 100 |
| SEO | 92 / 100 | 92 / 100 |
**⚡ Core Web Vitals & Key Metrics**
| Metric | Mobile Value | Desktop Value |
|-----------------|--------------|---------------|
| First Contentful Paint (FCP) | 2.9 s | 0.7 s |
| Largest Contentful Paint (LCP) | 4.8 s | 1.2 s |
| Total Blocking Time (TBT) | 0 ms | 0 ms |
| Cumulative Layout Shift (CLS) | 0.336 | 0.114 |
| Speed Index (SI) | 2.9 s | 0.7 s |
應用程式的行動裝置效能分數為 61 分 (滿分 100 分)。查詢 modern-web-guidance,取得將應用程式最佳化以在行動裝置上執行的建議,並提高效能分數。
5. 查詢以提升效能
如要評估標準基礎模型產生的建議與啟用 modern-web-guidance 時的建議差異,請在要求代理程式提供成效最佳化建議時,進行比較測試。
首先,請先查詢基礎模型,瞭解模型建議的行動版網頁效能提升方式,不必安裝 modern-web-guidance。
看到網頁功能輸出內容,以及模型建議的原因後,請在另一個終端機視窗中安裝 modern-web-guidance,並接受所有預設值。
npx modern-web-guidance@latest install
返回 Antigravity,查詢新安裝的技能,並要求與基礎模型建議的清單進行比較。
● Bash(npx -y modern-web-guidance@latest search "performance")
⎿ [{"id":"performance","description":"Actionable guidelines for optimizing modern web applications. Use this guide when auditing performance, optimizing loading metrics, fixing slow interactions and optimizing Core Web Vitals (LCP, INP, CLS)","category":"performance","similarity":0.5569},
{"id":"efficient-background-processing","description":"Conserve system resources and battery life by pausing background JavaScript execution (such as `<canvas>` animations, WebGL rendering, or high-frequency WebSocket data polling) when the component is off-screen and then resume them just-in-time when they scroll back into view.","category":"performance","featuresUsed":["content-visibility"], "similarity":0.5066},
{"id":"html","description":"Action-oriented guidelines for modern HTML architecture, semantics, native interactive APIs (Dialog, Popover, Details), focus management, and resource prioritization. Use this
guide when structuring web documents, implementing native overlays, or optimizing resource loading order.","category":"html", "similarity":0.4478},
{"id":"faster-spa-view-transitions","description":"Enable faster transitions back to previously visited views in a Single-Page Application (SPA) by preserving their structural DOM state instead of
destroying and rebuilding them on every navigation.","category":"performance","featuresUsed":["content-visibility"], "similarity":0.444},
{"id":"identify-heavy-scripts","description":"Identify the scripts most responsible for long animation frames","category":"performance","featuresUsed":["Long animation
frames"], "similarity":0.4287}] (ctrl+o to collapse)
● Bash(npx -y modern-web-guidance@latest search "image")
⎿ [{"id":"deliver-optimized-decorative-images","description":"Deliver optimized decorative images (such as backgrounds, UI icons, or complex masks) by simultaneously providing next-generation image formats
(like AVIF or WebP) alongside multiple pixel densities (like 1x and 2x) so the browser can dynamically negotiate the best combination of file size and visual quality for the user's device
capabilities.","category":"user-experience","featuresUsed":["image-set()"], "similarity":0.4038},
{"id":"performance","description":"Actionable guidelines for optimizing modern web applications. Use this guide when auditing performance, optimizing loading metrics, fixing slow interactions and
optimizing Core Web Vitals (LCP, INP, CLS)","category":"performance", "similarity":0.3761},
{"id":"visually-texture-content","description":"Apply realistic weathering and texture patterns to elements to give them an organic, aged, or physical material
appearance.","category":"user-experience","featuresUsed":["Masks"], "similarity":0.3716},
{"id":"resolution-optimized-pseudo-elements","description":"Use resolution-optimized images in CSS pseudo-elements (such as `::before` and `::after`) to reduce the number of DOM
nodes.","category":"performance","featuresUsed":["image-set()"], "similarity":0.3566},
{"id":"optimize-image-priority","description":"Optimize the loading priority of Largest Contentful Paint (LCP) candidate images and deprioritize non-critical images to reduce critical resource load
delays.","category":"performance","featuresUsed":["Fetch priority"],"similarity":0.32}] (ctrl+o to collapse)
● Bash(npx -y modern-web-guidance@latest retrieve "performance,optimize-image-priority")
⎿ <output +165 lines>
- **RECOMMENDED**: Avoid using `fetchpriority="auto"`. If you want the default priority, omit the attribute entirely to keep your HTML clean.
- **DO NOT** combine `fetchpriority="high"` with `loading="lazy"` for the LCP image.
- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority` and is not supported by any browser.
## Fallback strategy
Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.
Supported by: Chrome 103 (Jun 2022), Edge 103 (Jun 2022), Firefox 132 (Oct 2024), and Safari 17.2 (Dec 2023).
The `fetchpriority` attribute is a progressive enhancement for the `<img>` element. If a browser does not support it, the attribute is ignored, and the browser uses its default priority heuristics. (ctrl+o
to collapse)
代理程式完成推論後,會顯示比較分析,說明模型在有/沒有 modern-web-guidance 技能時的建議,並醒目顯示重疊的建議。下列輸出內容取決於 Gemini 模型版本和目前的 modern-web-guidance 版本。
由於本機環境可能有所不同,請在 GitHub 存放區中開啟問題,分享您使用 Modern Web Guidance 的具體結果和意見回饋。
代理程式的輸出內容應與下列內容類似:
### 1. Base Model Knowledge Recommendations (Internal Training Only)
Based purely on standard web development practices, the following steps are recommended to improve the application's mobile performance score:
• Hero Image Optimization: Move the dynamic Javascript-loaded hero image into the source HTML file ( index.html ) so the browser preload scanner can fetch it immediately. Add fetchpriority="high" and serve the image in modern WebP
or AVIF formats.
• Layout Stability (CLS): Provide explicit width and height dimensions in HTML image elements so the browser can calculate the layout box size before the image has finished loading.
• Payload Compression: Minify JS and CSS bundles and compress images to reduce the 6.1 MB payload.
• Resource Optimization: Defer non-critical scripts and lazy-load offscreen/below-the-fold images.
──────
### 2. Fetched Modern Web Guidance Guides
The following official performance guides were successfully fetched and inspected from the repository's local skills folder:
1. optimize-image-priority.md
2. improve-next-page-load-performance.md
3. performance.md
──────
### 3. Comparison & Key Constraints Comparison
Below is the side-by-side comparison of the base model recommendations against the fetched performance guidelines:
| Optimization Area | Base Model Recommendation | Modern Web Guidance Rule | Mandatory Constraints & Discrepancies |
|---|---|---|---|
| Lazy Loading & Fetch Priority Interaction | Standard separation of lazy-load and high priority. | MANDATORY: Do not combine fetchpriority="high" with loading="lazy" on LCP images, and do not use fetchpriority="low" on standard below-the-fold lazy-loaded images. | Constraint: Below-the-fold lazy-loaded images must load at normal priority when they enter the viewport; low priority is reserved strictly for hidden above-the-fold content. |
| Speculative Loading | Preload the next page elements or assets generally. | DO: Use the Speculation Rules API (JSON-based script) to prefetch or prerender pages the user will likely visit next. | Discrepancy: The base model recommends traditional asset preloads. The guide introduces modern speculation rules (list and document rules). |
| Speculative Loading Restrictions | Standard speculative prefetching. | DO NOT use speculation rules on Single Page Applications (SPAs). DO NOT speculate URLs that trigger state changes (e.g., /logout , /add-to-cart ). | Constraint: Explicitly blocks speculation rules for SPA routers and state-changing actions to prevent unintentional sessions/actions from being triggered by background browser requests. |
| Main Thread & INP | Break up long tasks and throttle events. | DO: Implement the 50ms rule: any script execution > 50ms must yield to the main thread. Use scheduler.yield() with a Promise fallback. | Constraint: Explicitly forbids relying only on setTimeout(..., 0) because it places continuations at the back of the queue, potentially starving user input. |
| CSS Content Visibility | Standard style minification. | DO: Pair content-visibility: auto with contain-intrinsic-size for offscreen elements on large, complex pages only. | Constraint: Forbids using content-visibility: auto on simple/small pages or above-the-fold content due to overhead and jumping risks. |
如要進一步瞭解比較結果,請參閱下表:
最佳化領域 | 基礎模型建議 | Modern Web Guidance 規則 | 強制限制和差異 |
延遲載入和擷取優先順序互動 | 延遲載入和高優先順序的標準分隔。 | 必要條件:請勿在 LCP 圖片上同時使用 | 限制:延遲載入的需捲動位置以下圖片進入可視區域時,必須以一般優先順序載入;低優先順序嚴格保留給隱藏的需捲動位置以上內容。 |
推測載入 | 預先載入下一個網頁元素或素材資源。 | 建議:使用 Speculation Rules API (以 JSON 為基礎的指令碼),預先擷取或預先轉譯您接下來可能會造訪的網頁。 | 差異:基礎模型建議預先載入基本資產。本指南將介紹新式推測規則 (清單和文件規則)。 |
推測載入限制 | 標準推測預先擷取。 | 請勿在單頁應用程式 (SPA) 中使用推測規則。請勿推測會觸發狀態變更的網址 (例如 | 限制:明確封鎖 SPA 路由器和狀態變更動作的推測規則,防止背景瀏覽器要求觸發非預期的工作階段或動作。 |
主執行緒和 INP | 拆分長時間執行的工作,並節流事件。 | 建議:實作 50 毫秒規則:任何執行時間超過 50 毫秒的指令碼都必須讓給主執行緒。使用 | 限制:明確禁止僅依賴 |
CSS 內容瀏覽權限 | 標準樣式壓縮。 | 建議:只針對大型複雜網頁上的畫面外元素,將 | 限制:禁止在較簡單的頁面或不需捲動位置的內容上使用 |
從表格中可以看出,基礎模型瞭解如何提升成效,但 modern-web-guidance 會將這些廣泛的建議細化為嚴格的規則。
在「Lazy loading & fetch priority interaction」一節中,基礎模型會辨識出 loading="lazy" 是良好的做法,但技能會提供重要資訊:請勿將 fetchpriority="low" 與 loading="lazy" 屬性合併使用。使用 AI 代理程式編碼時,這項強制執行功能非常實用。
代理瞭解嚴格的 modern-web-guidance 規則後,請代理草擬這兩種方法的程式碼,查看實作上的差異。
查看代理程式建議的方案:
▾ Thought for 2s
Formulating Mobile Optimization Plans
Okay, I'm currently focused on crafting two mobile optimization plans as
requested. I'm structuring them specifically for both a base model and one
leveraging modern-web-guidance. I'm adding sources and baselines to each for
comparison. My goal is to present these plans to you for review before any
implementation begins. I'm trying to make sure I get this exactly right.
...
● ListDir(modern-web-guidance-demos/legacy-demos/cozy-nook-bookshop/static/assets)
⎿ 8 files, 0 directories (ctrl+o to collapse)
Below are two implementation plans to optimize the mobile performance of The
Cozy Nook to a 90+ score.
──────
### Plan A: Base Model Only (Traditional Web Performance)
This plan uses classic web performance optimization patterns based on general
knowledge from standard MDN/web.dev documentation.
#### Proposed Changes
1. LCP Hero Image HTML Declaration:
• Modify index.html to include the static hero image source directly:
<img src="./assets/hero-img.png" alt="Old Books stack on wooden table" class="hero-img">
• Remove the dynamic JS source injection in hero.js to prevent JS execution delay blocking the render.
2. Critical Preload Link:
• Add a preload link in the <head> of index.html to prioritize the asset request:
<link rel="preload" as="image" href="./assets/hero-img.png">
3. Cumulative Layout Shift (CLS) Fixes:
• Add explicit width and height dimensions to all static image elements in index.html (e.g., hero, staff picks, avatars).
#### Sources & References
• Preloading Assets: MDN Web Docs - Preloading Content https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preload
• CLS Prevention: web.dev - Optimize Cumulative Layout Shift https://web.dev/articles/cls
### Plan B: Modern Web Guidance (Recommended)
This plan strictly follows Google Chrome's modern guidelines, progressive
enhancements, and rules. It minimizes resource contention and leverages native
speculation tools.
#### Proposed Changes
1. HTML Declaration with Native Fetch Priority:
• Modify index.html to load the hero image inline and declare priority:
<img src="./assets/hero-img.png" fetchpriority="high" alt="Old Books stack on wooden table" class="hero-img">
• Constraint Met: Do not add a duplicate <link rel="preload">. Modern web
guidance mandates letting the browser's preload scanner natively discover
the raw HTML image tag. Adding a separate preload resource block causes
unnecessary network overhead.
• Remove the dynamic source loading in hero.js.
2. Explicit Layout Boundaries (CLS):
• Set physical width and height attributes matching the design aspect
ratio directly on the hero, pick covers, and avatar elements inside
index.html.
3. Speculative MPA Navigation (Next-page optimization):
• Since this is a Multi-Page Application (MPA), embed a Speculation Rules
script block in the bottom of index.html to prefetch same-origin routes
(about.html, contact.html, details.html) with moderate eagerness with
script type "speculationrules" with the following content.
{
"prefetch": [{
"where": {
"and": [
{ "href_matches": "/*" },
{ "not": { "href_matches": "/basket.html" } }
]
},
"eagerness": "moderate"
}]
}
• Constraint Met: We explicitly exclude shopping checkout items like
basket.html from prefetching to avoid unnecessary/accidental request
triggers.
#### Sources & References
• optimize-image-priority.md
• improve-next-page-load-performance.md
• performance.md
6. 比較無引導式與有引導式導入方式
以下是使用 Gemini 和 modern-web-guidance 進行比較測試時,這個書店應用程式的代理程式輸出內容範例。
您的結果可能與我們不同,因此請使用這項策略,而非嚴格的步驟。您可以透過這些方案,瞭解在電腦上為書店應用程式啟用 modern-web-guidance 後,情況會如何變化。自行完成比較測試後,請詢問代理商,哪種方法最適合您的特定設定。
您可以透過 Lighthouse 或 DevTools for Agents 追蹤應用程式的效能,查看更新後實際改善情形。
1. 延遲載入和擷取優先順序互動
最佳化螢幕外圖片,避免主要執行緒頻寬爭用。
方案 A (基本型號)
對所有畫面外圖片套用標準 loading="lazy"。(不理想:延遲載入畫面外的資產,但讓可見的非 LCP 首要內容資產與 LCP 圖片競爭)。
<img src="https://..." alt="..." class="pick-small-img" loading="lazy">
方案 B (Modern Web Guidance)
使用 fetchpriority="low" 鎖定最初在首頁上方不可見的元素,並確保標準延遲載入圖片維持預設優先順序。(最佳做法:降級會封鎖重要算繪路徑的隱藏資產,但不會延長捲動載入時間。)
<img src="https://..." fetchpriority="low" width="96" height="144" alt="..." class="pick-small-img" loading="lazy">
2. 推測載入
預先擷取下一個頁面的文件或資產,加快日後載入網頁的速度。
方案 A (基本型號)
這種做法會使用 元素。(不盡理想:子頁面轉場效果仍有約 1 秒的延遲。)
<link rel="prefetch" href="about.html">
<link rel="prefetch" href="contact.html">
方案 B (Modern Web Guidance)
使用 Speculation Rules API。(最佳做法:推測規則可讓您使用相符的查詢執行預先擷取和預先算繪,縮短導覽時間。)
<script type="speculationrules">
{
"prefetch": [{
"where": { "href_matches": "/*" },
"eagerness": "moderate"
}]
}
</script>
3. 推測載入限制
明確禁止預先擷取特定網頁 (例如 /logout 或 /basket.html),避免發生安全性、效能或狀態衝突。
方案 A (基本型號)
這種做法需要開發人員手動管理要加入的網址。(不理想:這種做法有風險,因為無意間的背景動作會造成更高的安全風險)。
方案 B (Modern Web Guidance)
這種方法會以宣告方式排除管理、具狀態或購物路徑。(最佳做法:程式輔助排除條件可防止瀏覽器執行非預期的背景動作)。
<script type="speculationrules">
{
"prefetch": [{
"where": {
"and": [
{ "href_matches": "/*" },
{ "not": { "href_matches": "/wp-admin/*" } },
{ "not": { "href_matches": "/basket.html" } },
{ "not": { "selector_matches": ".do-not-prerender" } }
]
},
"eagerness": "moderate"
}]
}
</script>
4. 主執行緒和 Interaction to Next Paint (INP)
優先處理使用者輸入內容的主執行緒,維持高回應速度。
方案 A (基本模型):
使用同步回呼迴圈延後執行大量運算。(不理想:如果網頁的主執行緒忙碌,您可能會遇到 Interaction to Next Paint (INP) 偏高的情況)。
function renderBigCatalog(items) {
items.forEach(item => {
renderItem(item);
});
}
方案 B (Modern Web Guidance):
如要讓主執行緒保持回應,請使用 scheduler.yield() 讓出主執行緒。(最佳做法:使用 scheduler.yield() 方法可確保輸入內容保持回應,不會發生工作資源不足的情況。)
async function yieldToMain() {
if ('scheduler' in window && 'yield' in scheduler) {
return await scheduler.yield();
}
return new Promise(resolve => setTimeout(resolve, 0));
}
async function renderBigCatalog(items) {
for (let i = 0; i < items.length; i++) {
renderItem(items[i]);
if (i % 50 === 0) {
await yieldToMain();
}
}
}
5. CSS content-visibility
延後螢幕外元素的算繪作業,藉此管理螢幕外版面配置計算。
方案 A (基本型號)
縮減樣式表組合。(不理想:初始繪製時的標準算繪負荷。)
.book-item {
display: flex;
margin: 1rem;
}
方案 B (Modern Web Guidance)
略過繪製螢幕外元素,直到這些元素接近可視區域邊界為止。(最佳做法:避免大型網頁在行動裝置上顯示時造成額外負擔。modern-web-guidance 工具可確保 content-visibility 僅套用至畫面外元素,並與 contain-intrinsic-size 配對。如果沒有這個脈絡,基礎模型可能會將其套用至全域,導致捲動時發生重大版面配置變化。
.book-item {
display: flex;
margin: 1rem;
content-visibility: auto;
contain-intrinsic-size: auto 350px;
}
7. 導入及驗證
分析差異並確認方案 B 是最佳做法後,即可將其套用至專案。您現在可以查看這些現代網頁指南規則對實際 Lighthouse 分數的影響。
代理程式會套用內建的 fetchpriority、設定 Speculation Rules API,並新增微工作產生作業。最終 Lighthouse 報表產生後,行動裝置分數會從原本的 61 分 (滿分 100 分) 提高。
您已正式將舊版程式碼現代化。
8. 根據優先順序進行疊代
這個方法會在您套用 modern-web-guidance 時評估應用程式,並評估應用程式是否遵循現代網頁開發最佳做法。隨著進度推進,請嘗試不同的設定:
- 新增功能:建議使用捲動時會隱藏的浮動標題,盡量擴大螢幕空間。
- 嘗試不同的基準目標:變更專案中的基準狀態,觀察效果。
- 專注於特定領域,並觀察不同選擇對程式碼基底的影響。
反覆運算可協助您處理大型或舊版應用程式的複雜性;精簡、測試、建構,然後重複執行。
9. 後續步驟
如要進一步瞭解如何使用 Modern Web Guidance,請參閱 Modern Web Guidance 指令說明文件和 DevTools for Agents。
如果您對 Modern Web Guidance 有任何問題或意見回饋,請在 GitHub 存放區中回報問題。