1. 최신 웹 가이드란 무엇인가요?
최신 웹 가이드는 최신 권장사항과 브라우저 호환성을 코딩 에이전트에 직접 적용합니다. 이러한 기술을 사용하면 코드가 현재 웹 플랫폼 기능과 계속 일치합니다. 최신 웹 가이드는 새로운 프로토타입 개발부터 레거시 시스템 리팩터링까지 최신 웹 표준에 대한 액세스를 제공합니다.
개발자는 이를 사용하여 다음 작업을 할 수 있습니다.
- 견고한 기반을 구축합니다. 상호 운용 가능한 웹 기능을 사용하는 프로젝트를 시작합니다.
- 레거시 코드를 현대화합니다. 일반적인 사용자 인터페이스 패턴의 맞춤 구현을 대체합니다.
- 개발하면서 학습합니다. 이 스킬은 개발 중에 문맥 인지 가이드를 제공하므로 최신 웹 패턴에 관한 지식을 개선합니다.
레거시 앱을 감사하고 기준 타겟을 설정하며 표준 AI 추천을 최신 웹 가이드 규칙과 대조하면 오래되었거나 일반적인 모델 출력을 사용하는 대신 최신 웹 가이드가 개선된 코딩 에이전트가 고성능의 최신 웹 코드를 생성하도록 프롬프트를 표시하는 방법을 알 수 있습니다.
2. 기본 요건
이 Codelab을 시작하기 전에 다음 지식을 보유하고 있는지 확인하세요.
- 최신 웹 가이드 문서 및 에이전트에 구애받지 않는 설치
- 기준 및 Lighthouse에 관한 기본 이해
- 프롬프트에 관한 기본 이해
이 Codelab에서는 다음을 사용합니다.
- 최신 웹 가이드 (v0.0.173)
- Antigravity CLI (Gemini 3.5 Flash 포함 v1.0.10)
이 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. 기준 타겟 설정
기준은 현재 브라우저에서 상호 운용 가능한 기능에 관한 정보를 제공합니다. 또한 브라우저 엔진과 버전을 지정하지 않고도 지원하려는 브라우저를 표현하는 방법을 제공합니다. 기능이 상호 운용 가능하면 기준이 되는 것으로 간주됩니다.
웹 애플리케이션을 개발하기 전에 기준 타겟을 선택하세요. 기본적으로 modern-web-guidance는 최소 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 스킬이 속도를 개선하는 방법을 중점적으로 살펴봅니다. 에이전트가 수행하는 변경사항을 모니터링하고 결과가 프로젝트 목표와 일치하는지 확인하려면 한 번에 하나의 작업에 집중하세요.
시작하려면 서점 앱이 초기 상태에서 어떻게 작동하는지 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 |
앱은 모바일에서 성능 점수가 100점 만점에 61점입니다. 모바일에 맞게 앱을 최적화하고 성능 점수를 개선하기 위한 추천을 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 저장소에서 문제를 열어 최신 웹 가이드에 관한 구체적인 결과와 의견을 공유하세요.
에이전트의 출력은 다음과 비슷해야 합니다.
### 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. |
비교를 자세히 살펴보려면 다음 표를 참고하세요.
최적화 영역 | 기본 모델 추천 | 최신 웹 가이드 규칙 | 필수 제약 조건 및 불일치 |
지연 로드 및 가져오기 우선순위 상호작용 | 지연 로드 및 높은 우선순위의 표준 분리 | 필수: LCP 이미지에서 | 제약 조건: 스크롤 없이 보이는 지연 로드 이미지는 뷰포트에 들어갈 때 일반 우선순위로 로드되어야 합니다. 낮은 우선순위는 스크롤 없이 보이는 숨겨진 콘텐츠에만 엄격하게 예약됩니다. |
추측 로드 | 일반적으로 다음 페이지 요소 또는 애셋을 미리 로드합니다. | 실행: Speculation Rules API (JSON 기반 스크립트)를 사용하여 다음에 방문할 가능성이 높은 페이지를 프리페치하거나 사전 렌더링합니다. | 불일치: 기본 모델은 기본 애셋 미리 로드를 추천합니다. 이 가이드에서는 최신 추측 규칙 (목록 및 문서 규칙)을 소개합니다. |
추측 로드 제한사항 | 표준 추측 프리페치 | 단일 페이지 애플리케이션 (SPA)에서 추측 규칙을 사용하지 마세요. 상태 변경을 트리거하는 URL (예: | 제약 조건: 의도치 않은 세션 또는 작업이 백그라운드 브라우저 요청에 의해 트리거되는 것을 방지하기 위해 SPA 라우터 및 상태 변경 작업의 추측 규칙을 명시적으로 차단합니다. |
기본 스레드 및 INP | 긴 작업을 나누고 이벤트를 제한합니다. | 실행: 50ms 규칙을 구현합니다. 50ms보다 긴 스크립트 실행은 기본 스레드에 양보해야 합니다. Promise 대체와 함께 | 제약 조건: |
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로 앱의 성능을 추적하여 실제 개선사항을 확인할 수 있습니다.
1. 지연 로드 및 가져오기 우선순위 상호작용
기본 스레드 대역폭 경합을 방지하기 위해 화면 밖 이미지를 최적화합니다.
계획 A (기본 모델)
모든 화면 밖 이미지에 표준 loading="lazy"를 적용합니다. (최적이 아님: 화면 밖 애셋을 지연 로드하지만 스크롤 없이 보이는 비 LCP 애셋이 LCP 이미지와 경쟁하도록 허용합니다.)
<img src="https://..." alt="..." class="pick-small-img" loading="lazy">
계획 B (최신 웹 가이드)
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 (최신 웹 가이드)
Speculation Rules API를 사용합니다. (최적의 옵션: 추측 규칙을 사용하면 일치하는 쿼리로 프리페치 및 사전 렌더링을 실행하여 인식되는 탐색 시간을 줄일 수 있습니다.)
<script type="speculationrules">
{
"prefetch": [{
"where": { "href_matches": "/*" },
"eagerness": "moderate"
}]
}
</script>
3. 추측 로드 제한사항
특정 페이지가 프리페치되지 않도록 명시적으로 차단하여 보안, 성능 또는 상태 충돌을 방지합니다(예: /logout 또는 /basket.html).
계획 A (기본 모델)
이 접근 방식에서는 개발자가 포함할 URL을 수동으로 관리해야 합니다. (최적이 아님: 이 접근 방식은 의도치 않은 백그라운드 작업의 보안 위험을 높이므로 위험합니다.)
계획 B (최신 웹 가이드)
이 접근 방식은 관리, 상태 저장 또는 쇼핑 경로를 선언적으로 제외합니다. (최적의 옵션: 프로그래매틱 제외는 브라우저가 의도치 않은 백그라운드 작업을 실행하지 못하도록 합니다.)
<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. 기본 스레드 및 다음 페인트에 대한 상호작용 (INP)
높은 응답성을 유지하기 위해 사용자 입력에 기본 스레드 가용성의 우선순위를 지정합니다.
계획 A (기본 모델):
동기 콜백 루프를 사용하여 과도한 계산을 연기합니다. (최적이 아님: 페이지에 사용 중인 기본 스레드가 있는 경우 다음 페인트에 대한 상호작용 (INP)이 높을 수 있습니다.)
function renderBigCatalog(items) {
items.forEach(item => {
renderItem(item);
});
}
계획 B (최신 웹 가이드):
기본 스레드의 응답성을 유지하려면 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 도구는 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 보고서가 생성되면 모바일 점수가 초기 100점 만점에 61점에서 증가합니다.
레거시 코드를 공식적으로 현대화했습니다.
8. 우선순위에 따라 반복
이 접근 방식은 modern-web-guidance를 적용할 때 애플리케이션을 평가하고 최신 웹 개발 권장사항을 준수하는 방법을 평가합니다. 계속 진행하면서 다양한 구성을 실험해 보세요.
- 새 기능 추가: 스크롤하는 동안 숨겨져 화면 공간을 극대화하는 플로팅 헤더를 추천합니다.
- 다양한 기준 타겟으로 실험: 프로젝트에서 기준 상태를 전환하여 효과를 관찰합니다.
- 특정 분야에 집중 하고 다양한 선택이 코드베이스에 미치는 영향을 관찰합니다.
반복을 통해 대규모 또는 레거시 애플리케이션의 복잡성을 탐색하고, 구체화하고, 테스트하고, 빌드하고, 반복할 수 있습니다.
9. 다음 단계
최신 웹 가이드 사용에 관한 자세한 내용은 최신 웹 가이드 명령어 문서 및 에이전트용 DevTools를 참고하세요.
최신 웹 가이드에 관한 질문이나 의견이 있으면 GitHub 저장소에서 문제를 제출하세요.