Modern Web Guidance 101

1. Modern Web Guidance とは

Modern Web Guidanceは、最新のベスト プラクティスとブラウザの互換性をコーディング エージェントに直接適用します。これらのスキルにより、コードが現在のウェブ プラットフォームの機能と一致した状態を維持できます。新しいプロトタイプの開発からレガシー システムのリファクタリングまで、Modern Web Guidance を使用すると、最新のウェブ標準にアクセスできます。

デベロッパーは、この API を使用して次のことができます。

  • 確固たる基盤の上に構築する: 相互運用可能なウェブ機能を使用するプロジェクトを開始します。
  • レガシー コードを最新化する: 共通のユーザー インターフェース パターンのカスタム実装を置き換えます。
  • 開発しながら学習する: スキルが開発中にコンテキスト認識型のガイダンスを提供するため、最新のウェブ パターンに関する知識を深めることができます。

レガシーアプリを監査し、ベースライン ターゲットを設定し、標準の AI の提案と Modern Web Guidance ルールを比較することで、最新のウェブ ガイダンスが強化されたコーディング エージェントにプロンプトを送信して、古いモデル出力や一般的なモデル出力に頼るのではなく、パフォーマンスの高い最新のウェブコードを生成する方法を学びます。

2. 前提条件

この Codelab を始める前に、次の知識があることを確認してください。

この Codelab では、次のものを使用します。

この Codelab は、意図的にレガシー コードで構成されたレガシーの「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 ファイルに適切なベースライン ターゲットを含める必要があります。

この Codelab では、このプロジェクトは 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 を最適化します。
  • ユーザー エクスペリエンス: 操作性とユーザビリティを向上させます。
  • ユーザー補助: ユーザー補助の問題に対処して、アプリケーションへのアクセスを拡大します。
  • フォームとセキュリティ: 入力処理を最新化し、アプリケーションのデータ入力ポイントを強化します。

この Codelab では、従来の書店アプリのパフォーマンスを比較し、Modern Web Guidance のスキルによって速度がどのように向上するかを確認します。一度に 1 つのタスクに集中して、エージェントが行う変更をモニタリングし、結果がプロジェクトの目標と一致していることを確認します。

まず、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

マークダウンを開くと、次のような結果が得られます。

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 バージョンによって異なります。

ローカル環境は異なる可能性があるため、Modern Web Guidance に関する具体的な結果とフィードバックは、GitHub リポジトリで問題をオープンして共有してください。

エージェントの出力は次のようになります。

 ### 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 画像で fetchpriority="high"loading="lazy" を組み合わせないでください。また、標準のファーストビュー外の遅延読み込み画像で fetchpriority="low" を使用しないでください。

制約: スクロールせずに見える範囲外の遅延読み込みされる画像は、ビューポートに入ったときに通常の優先度で読み込まれる必要があります。低優先度は、スクロールせずに見える範囲内の非表示コンテンツにのみ厳密に予約されています。

投機的読み込み

一般的に、次のページの要素やアセットをプリロードします。

推奨: Speculation Rules API(JSON ベースのスクリプト)を使用して、次にアクセスする可能性の高いページをプリフェッチまたはプリレンダリングします。

不一致: ベースモデルでは、基本的なアセットのプリロードが推奨されています。このガイドでは、最新の投機ルール(リストルールとドキュメント ルール)について説明します。

投機的読み込みの制限

標準の投機的プリフェッチ。

シングルページ アプリケーション(SPA)では投機ルールを使用しないでください。状態の変化(/logout/add-to-cart など)をトリガーする URL を推測しないでください。

制約: SPA ルーターと状態変更アクションの投機ルールを明示的にブロックし、バックグラウンド ブラウザ リクエストによって意図しないセッションやアクションがトリガーされるのを防ぎます。

メインスレッドと INP

長いタスクを分割し、イベントをスロットリングします。

推奨: 50 ミリ秒ルールを実装します。50 ミリ秒を超えるスクリプト実行はメインスレッドに譲る必要があります。Promise フォールバックで scheduler.yield() を使用します。

制約: setTimeout(..., 0) のみに依存することを明示的に禁止します。これは、継続をキューの末尾に配置し、ユーザー入力が不足する可能性があるためです。

CSS のコンテンツの公開設定

標準的なスタイルの最小化。

推奨: 大きく複雑なページのオフスクリーン要素に対してのみ、content-visibility: autocontain-intrinsic-size をペアにします。

制約: オーバーヘッドとジャンプのリスクがあるため、シンプルなページやファーストビューのコンテンツで content-visibility: auto を使用することは禁止されています。

この表から、ベースモデルはパフォーマンスを向上させる方法を理解しているものの、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">

プラン 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 を使用します。(最適なオプション: 推測ルールを使用すると、一致するクエリでプリフェッチと事前レンダリングを実行して、認識される Navigation 時間を短縮できます)。

<script type="speculationrules">
  {
    "prefetch": [{
      "where": { "href_matches": "/*" },
      "eagerness": "moderate"
    }]
  }
</script>

3. 投機的読み込みの制限

たとえば、/logout/basket.html などの特定のページを明示的にプリフェッチしないようにブロックすることで、セキュリティ、パフォーマンス、状態の競合を防ぎます。

プラン A(ベースモデル)

この方法では、デベロッパーが含める URL を手動で管理する必要があります。(最適ではない: このアプローチは、意図しないバックグラウンド アクションによるセキュリティ リスクを高めるため、危険です)。

プラン 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 が最適なアプローチであると判断したら、プロジェクトに適用できます。これらの Modern Web Guidance ルールが実際の Lighthouse スコアにどのように影響するかを確認できるようになりました。

エージェントは組み込みの fetchpriority を適用し、Speculation Rules API を設定して、マイクロタスクのイールドを追加します。最終的な Lighthouse レポートが生成されると、モバイル スコアは最初の 100 点満点中 61 点から上昇します。

これで、以前のコードのモダナイズが完了しました。

8. 優先順位に基づいて反復する

このアプローチでは、modern-web-guidance を適用するときにアプリケーションを評価し、最新のウェブ開発のベスト プラクティスに準拠しているかどうかを評価します。次に進むにあたって、さまざまな構成を試してみます。

  • 新機能を追加: スクロール時に非表示になるフローティング ヘッダーを推奨して、画面スペースを最大限に活用します。
  • さまざまなベースライン ターゲットでテストする: プロジェクトのベースライン ステータスを変更して、効果を確認します。
  • 特定の分野に焦点を当て、さまざまな選択肢がコードベースにどのように影響するかを観察します。

イテレーションは、大規模なアプリケーションやレガシー アプリケーションの複雑さを解消するのに役立ちます。洗練、テスト、ビルドを繰り返します。

9. 次のステップ

Modern Web Guidance の使用について詳しくは、Modern Web Guidance コマンドのドキュメントDevTools for Agents をご覧ください。

Modern Web Guidance に関するご質問やフィードバックがございましたら、GitHub リポジトリで問題を報告してください。