1. 什么是 Modern Web Guidance?
Modern Web Guidance可直接将现代最佳实践和浏览器兼容性应用于您的编码智能体。这些技能可确保您的代码与当前的 Web 平台功能保持一致。无论是开发新原型还是重构旧版系统,Modern Web Guidance 都能让您访问现代 Web 标准。
开发者可以使用该功能来执行以下操作:
- 打造坚实的基础:启动使用可互操作的 Web 功能的项目。
- 使旧版代码现代化:替换常见界面模式的自定义实现。
- 在开发过程中学习:在技能提供情境感知指导的过程中,提高您对现代 Web 模式的了解。
通过审核旧版应用、设置 Baseline 目标,并将标准 AI 建议与 Modern Web Guidance 规则进行对比,您可以学会提示 Modern Web Guidance 增强型编码智能体生成高性能的现代 Web 代码,而不是依赖过时或通用的模型输出。
2. 前提条件
在开始此 Codelab 之前,请确保您具备以下知识:
- Modern Web Guidance 文档和与代理无关的安装
- 对 Baseline 和 Lighthouse 有基本的了解
- 对提示有基本的了解
本 Codelab 使用以下内容:
- Modern Web Guidance (v0.0.173)
- Antigravity CLI(搭载 Gemini 3.5 Flash,版本为 1.0.10)
本 Codelab 从一个有意使用旧版代码组成的旧版“Cozy Nook”应用开始。克隆演示代码库,然后前往 cozy-nook-bookshop Web 应用。
git clone git@github.com:GoogleChromeLabs.modern-web-guidance-demos.git
cd modern-web-guidance-demos/legacy-demos/cozy-nook-bookshop/
3. 设置基准目标值
Baseline 提供有关目前哪些功能可在浏览器中互操作的信息。它还提供了一种表达您要支持哪些浏览器的方式,而无需指定浏览器引擎和版本。如果某项功能可互操作,则会被视为 Baseline 功能。
在开发 Web 应用之前,请选择基准目标。默认情况下,modern-web-guidance 使用“Baseline 广泛可用”,其中包括已实现互操作至少 30 个月的功能。如果您需要支持更新的功能,则需要在 AGENTS.md 文件中添加相应的基准目标平台。
在本 Codelab 中,此项目使用固定的目标 baseline widely available on 2026-06-01。
// AGENTS.md
This project's Baseline target is "Baseline widely available on 2026-06-01".
4. 确定项目优先级
选择基准目标后,定义优先级并批量处理相关功能和主题。采用增量改进的思维模式,就像您构建功能时一样。
根据特定的过时功能或更广泛的网络开发学科对更新进行分类,例如:
- 效果:优化核心网页指标。
- 用户体验:改进互动和易用性。
- 无障碍功能:解决无障碍功能问题,以扩大应用的使用范围。
- 表单和安全性:对输入处理进行现代化改造,并强化应用的数据输入点。
在此 Codelab 中,您将重点比较旧版书店应用的性能,以了解 Modern Web 指南技能如何提高其速度。一次专注于一项任务,以监控智能体执行的更改,并确保结果符合您的项目目标。
首先,使用 Lighthouse 审核清楚了解书店应用在初始状态下的表现。
在本地机器上打开 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 技能和没有 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 图片上将 | 限制:非首屏延迟加载的图片进入视口时必须以正常优先级加载;低优先级严格保留给隐藏的首屏内容。 |
推测加载 | 预加载下一个网页元素或素材资源(一般)。 | 建议:使用推测规则 API(基于 JSON 的脚本)预提取或预渲染您接下来可能会访问的网页。 | 差异:基本模型建议预加载基本素材资源。该指南介绍了现代推测规则(列表规则和文档规则)。 |
推测加载限制 | 标准推测性预取。 | 请勿在单页应用 (SPA) 上使用推测规则。不要推测触发状态更改(例如 | 限制:明确阻止 SPA 路由器和状态更改操作的推测规则,以防止后台浏览器请求触发意外会话或操作。 |
主线程和 INP | 拆分长时间运行的任务并限制事件。 | 做法:实现 50 毫秒规则:任何执行时间超过 50 毫秒的脚本都必须让位于主线程。将 | 限制:明确禁止仅依赖 |
CSS 内容可见性 | 标准样式缩减。 | 建议:仅在大型复杂网页上将 | 限制:禁止在较简单的网页或首屏内容中使用 |
该表格显示,基础模型了解如何提升性能,但 modern-web-guidance 将这些宽泛的建议细化为严格的规则。
在“延迟加载和提取优先级互动”部分,基础模型认为 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">
Plan B(现代 Web 指南)
使用 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">
Plan B(现代 Web 指南)
使用 Speculation Rules API。(最佳选择:借助推测规则,您可以执行预提取和预渲染,并使用匹配的查询来缩短感知到的导航时间。)
<script type="speculationrules">
{
"prefetch": [{
"where": { "href_matches": "/*" },
"eagerness": "moderate"
}]
}
</script>
3. 推测加载限制
通过明确阻止预提取某些网页(例如 /logout 或 /basket.html),防止出现安全性、性能或状态冲突。
方案 A(基础模型)
此方法要求开发者手动管理要包含的网址。(次优:这种方法存在风险,因为这会带来更高的安全风险,即意外的后台操作。)
Plan B(现代 Web 指南)
此方法以声明方式排除管理路径、有状态路径或购物路径。(最佳选择:程序化排除对象可防止浏览器执行意外的后台操作。)
<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;
}
Plan B(现代 Web 指南)
跳过绘制屏幕外元素,直到它们接近视口边界。(最佳选项:可防止大型网页产生移动设备呈现开销。modern-web-guidance 工具可确保 content-visibility 仅应用于屏幕外元素,并将其与 contain-intrinsic-size 配对。如果没有此上下文,基本模型可能会在全球范围内应用它,这可能会在滚动期间导致严重的布局偏移。)
.book-item {
display: flex;
margin: 1rem;
content-visibility: auto;
contain-intrinsic-size: auto 350px;
}
7. 实现和验证
在分析差异并确定方案 B 是优化方法后,您可以将其应用于项目。现在,您可以了解这些“新版 Web 指南”规则对实际 Lighthouse 分数有何影响。
代理应用内置的 fetchpriority,设置 Speculation Rules API,并添加微任务让步。生成最终的 Lighthouse 报告后,移动版得分从最初的 61 分(满分 100 分)提高。
您已正式将旧版代码现代化。
8. 根据优先级进行迭代
此方法会在您应用 modern-web-guidance 时评估您的应用,并评估其是否遵循现代 Web 开发最佳实践。随着您不断进步,可以尝试不同的配置:
- 添加新功能:建议使用在滚动时隐藏的浮动标题,以最大限度地利用屏幕空间。
- 尝试不同的基准目标值:更改项目中的基准状态,以观察效果。
- 专注于特定学科,并观察不同的选择如何影响您的代码库。
迭代有助于您应对大型应用或旧版应用的复杂性;优化、测试、构建并重复。
9. 后续步骤
如需详细了解如何使用“现代 Web 指南”,请参阅“现代 Web 指南”命令文档和代理的开发者工具。
如果您对 Modern Web Guidance 有任何疑问或反馈,请在 GitHub 代码库中提交问题。