@capagents/forgeqe 3.1.0 → 3.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOW_TO_USE.md +465 -95
- package/README.md +21 -6
- package/THIRD_PARTY_NOTICES.md +210 -1
- package/dist/docs-site/CREDITS.md +6 -0
- package/dist/docs-site/architecture-map/index.html +1 -1
- package/dist/docs-site/docs/app-theme.css +100 -8
- package/dist/docs-site/docs/architecture/index.html +210 -214
- package/dist/docs-site/docs/area-api/index.html +350 -0
- package/dist/docs-site/docs/area-automated-tests/index.html +967 -0
- package/dist/docs-site/docs/area-browser/index.html +430 -0
- package/dist/docs-site/docs/area-data/index.html +605 -0
- package/dist/docs-site/docs/area-desktop/index.html +755 -0
- package/dist/docs-site/docs/area-mobile/index.html +631 -0
- package/dist/docs-site/docs/area-operations/index.html +1069 -0
- package/dist/docs-site/docs/area-pull-requests/index.html +208 -0
- package/dist/docs-site/docs/area-quality/index.html +365 -0
- package/dist/docs-site/docs/area-release/index.html +320 -0
- package/dist/docs-site/docs/area-setup/index.html +1192 -0
- package/dist/docs-site/docs/area-systems/index.html +207 -0
- package/dist/docs-site/docs/area-test-cases/index.html +694 -0
- package/dist/docs-site/docs/containers/index.html +97 -104
- package/dist/docs-site/docs/cost-architecture/index.html +108 -112
- package/dist/docs-site/docs/custom-agents-first-run/index.html +19 -23
- package/dist/docs-site/docs/desktop/index.html +172 -162
- package/dist/docs-site/docs/desktop-ci/index.html +26 -33
- package/dist/docs-site/docs/evidence/index.html +253 -257
- package/dist/docs-site/docs/feature-test-prompts/index.html +66 -70
- package/dist/docs-site/docs/get-started/index.html +495 -0
- package/dist/docs-site/docs/graphify/index.html +42 -46
- package/dist/docs-site/docs/guardrails/index.html +17 -21
- package/dist/docs-site/docs/index.html +17 -6708
- package/dist/docs-site/docs/mobile/index.html +155 -162
- package/dist/docs-site/docs/model-routing/index.html +44 -51
- package/dist/docs-site/docs/overview/index.html +176 -0
- package/dist/docs-site/docs/product-graph/index.html +52 -55
- package/dist/docs-site/docs/product-knowledge/index.html +11 -15
- package/dist/docs-site/docs/product-views/index.html +53 -57
- package/dist/docs-site/docs/reference/index.html +379 -0
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/docs-site/docs/using/index.html +480 -0
- package/dist/docs-site/docs/web-app/index.html +147 -93
- package/dist/docs-site/security/index.html +930 -0
- package/dist/docs-site/security/security-theme.css +161 -0
- package/dist/docs-site/security/security.js +1465 -0
- package/dist/docs-site/vendor/react-18.3.1.production.min.js +31 -0
- package/dist/docs-site/vendor/react-dom-18.3.1.production.min.js +267 -0
- package/dist/docs-site/vendor/reactflow-11.11.4.umd.js +10 -0
- package/dist/forgeqe.js +2251 -1886
- package/dist/web/THIRD_PARTY_NOTICES.md +0 -136
- package/dist/web/assets/Agent-CPhmZdFX.js +8 -0
- package/dist/web/assets/AgentWork-BXdN9xgi.js +2 -0
- package/dist/web/assets/ApiTests-Do3xLjfB.js +10 -0
- package/dist/web/assets/Browse-WVkJT6Bs.js +2 -0
- package/dist/web/assets/Chat-CDc9UcQX.js +3 -0
- package/dist/web/assets/CommandPalette-BAZm62lV.js +1 -0
- package/dist/web/assets/Compare-Br6n9T9L.js +1 -0
- package/dist/web/assets/Cost-BBUyBu3Y.js +1 -0
- package/dist/web/assets/Data-Ch2DPEWp.js +6 -0
- package/dist/web/assets/Desktop-Qzoq-cQv.js +1 -0
- package/dist/web/assets/DesktopReview-CF_jQYAM.js +1 -0
- package/dist/web/assets/Evidence-C72Lj5_Q.js +1 -0
- package/dist/web/assets/Explore-ObkEpUyS.js +2 -0
- package/dist/web/assets/Features-CQzNo_WP.js +1 -0
- package/dist/web/assets/Flags-0-RniPJm.js +2 -0
- package/dist/web/assets/Flaky-BPJvNLCA.js +1 -0
- package/dist/web/assets/Impact-CfccsL_k.js +3 -0
- package/dist/web/assets/Jobs-T6m4zhDy.js +5 -0
- package/dist/web/assets/KindPage-BDUvWe2p.js +6 -0
- package/dist/web/assets/Migration-Dqeh4x5u.js +2 -0
- package/dist/web/assets/PageAgent-DNjzIgeY.js +1 -0
- package/dist/web/assets/Product-nYV_scOV.js +7 -0
- package/dist/web/assets/Production-CGSbEWVa.js +1 -0
- package/dist/web/assets/Quality-BIypojZm.js +1 -0
- package/dist/web/assets/Readiness-BlRjwJRg.js +1 -0
- package/dist/web/assets/Record-v2KLI-_Z.js +1 -0
- package/dist/web/assets/Regression-B-jSt4Jz.js +5 -0
- package/dist/web/assets/RelationGraph-8J98lOVG.js +1 -0
- package/dist/web/assets/Reports-GI4u6SyW.js +2 -0
- package/dist/web/assets/Response-mhBThq2b.js +9 -0
- package/dist/web/assets/Responsive-DXu7Ra7K.js +3 -0
- package/dist/web/assets/RunDiff-D0SHDNp0.js +1 -0
- package/dist/web/assets/Runs-C1Gjdi9M.js +2 -0
- package/dist/web/assets/Settings-BGGeuvyF.js +21 -0
- package/dist/web/assets/Steps-D-YG0eJy.js +2 -0
- package/dist/web/assets/TestCases-DC4w77eQ.js +1 -0
- package/dist/web/assets/TestData-CvKWRVVV.js +2 -0
- package/dist/web/assets/TestDebt-D8YzN29_.js +1 -0
- package/dist/web/assets/TestManagement-C5cDCqrD.js +1 -0
- package/dist/web/assets/Tosca-BGUv3RiJ.js +3 -0
- package/dist/web/assets/WhatsNew-B_Gyuv8O.js +1 -0
- package/dist/web/assets/agents-C0Jg2pN8.js +1 -0
- package/dist/web/assets/coverage-BMP6ELFJ.js +5 -0
- package/dist/web/assets/dataParts-DbeCj9ga.js +3 -0
- package/dist/web/assets/diff-BStuTmsN.js +2 -0
- package/dist/web/assets/families-BBFFrUlo.js +1 -0
- package/dist/web/assets/filters-CnAMr286.js +1 -0
- package/dist/web/assets/fold-D_O_VZui.js +1 -0
- package/dist/web/assets/head-CRo48rPt.js +1 -0
- package/dist/web/assets/highlight-BcFZIf59.js +4 -0
- package/dist/web/assets/index-B3JsM7tv.js +64 -0
- package/dist/web/assets/index-CafApcbZ.css +2 -0
- package/dist/web/assets/input-CtzK50ZF.js +1 -0
- package/dist/web/assets/jsx-runtime-LKYXHABd.js +1 -0
- package/dist/web/assets/line-icons-rdF8DYDJ.js +1 -0
- package/dist/web/assets/logos-D4oVWzqa.js +1 -0
- package/dist/web/assets/palette-DAaGSao7.js +1 -0
- package/dist/web/assets/paletteCommands-Co-RlQ8q.js +1 -0
- package/dist/web/assets/parts-D357Wolo.js +1 -0
- package/dist/web/assets/productParts-B8oHRCJF.js +1 -0
- package/dist/web/assets/qualityParts-BLkmIfDY.js +1 -0
- package/dist/web/assets/recordTest-Cez2sDJO.js +1 -0
- package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/web/assets/route-BloYJWgw.js +1 -0
- package/dist/web/index.html +12 -12
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/BASAL.md +1 -1
- package/docs/DESKTOP.md +20 -1
- package/docs/EVIDENCE.md +1 -1
- package/docs/MOBILE.md +4 -4
- package/docs/PRODUCT_KNOWLEDGE.md +2 -0
- package/docs/WEB_APP.md +114 -51
- package/docs/user-guide.html +463 -87
- package/forgeqe.example.yaml +3 -3
- package/package.json +1 -1
- package/prompts/page-differs.md +1 -1
- package/prompts/requests-rule.md +1 -1
- package/prompts/responsive-review.md +38 -0
- package/prompts/responsive-split.md +40 -0
- package/prompts/responsive.md +42 -0
- package/prompts/test-reviewer.md +1 -1
- package/prompts/test-rules.md +3 -4
- package/skills/web-guidance/LICENSE +202 -0
- package/skills/web-guidance/SKILL.md +76 -0
- package/skills/web-guidance/UPSTREAM +67 -0
- package/skills/web-guidance/references/accessibility/accessibility.md +585 -0
- package/skills/web-guidance/references/accessibility/accessible-error-announcement.md +302 -0
- package/skills/web-guidance/references/accessibility/accessible-generated-content.md +41 -0
- package/skills/web-guidance/references/accessibility/respect-os-text-scale.md +127 -0
- package/skills/web-guidance/references/css/responsive-design.md +16 -0
- package/skills/web-guidance/references/forms/autofill-address-form.md +86 -0
- package/skills/web-guidance/references/forms/autofill-payment-form.md +142 -0
- package/skills/web-guidance/references/forms/autofill-sign-in-form.md +145 -0
- package/skills/web-guidance/references/forms/autofill-sign-up-form.md +155 -0
- package/skills/web-guidance/references/forms/forms.md +415 -0
- package/skills/web-guidance/references/forms/ime-safe-enter-submit.md +115 -0
- package/skills/web-guidance/references/forms/required-field-feedback.md +317 -0
- package/skills/web-guidance/references/forms/select-menu-interaction.md +310 -0
- package/skills/web-guidance/references/forms/slider.md +184 -0
- package/skills/web-guidance/references/forms/sms-otp-form.md +208 -0
- package/skills/web-guidance/references/forms/switch.md +60 -0
- package/skills/web-guidance/references/forms/validate-input-after-interaction.md +406 -0
- package/skills/web-guidance/references/performance/break-up-long-tasks.md +64 -0
- package/skills/web-guidance/references/performance/identify-heavy-scripts.md +69 -0
- package/skills/web-guidance/references/performance/identify-inp-causes.md +105 -0
- package/skills/web-guidance/references/performance/interaction-paint-timing.md +200 -0
- package/skills/web-guidance/references/performance/optimize-image-priority.md +73 -0
- package/skills/web-guidance/references/performance/performance.md +384 -0
- package/skills/web-guidance/references/privacy/privacy.md +247 -0
- package/skills/web-guidance/references/security/passkey-authentication.md +218 -0
- package/skills/web-guidance/references/security/passkey-management.md +310 -0
- package/skills/web-guidance/references/security/passkey-reauthentication.md +142 -0
- package/skills/web-guidance/references/security/passkey-registration.md +186 -0
- package/skills/web-guidance/references/security/passkeys.md +39 -0
- package/skills/web-guidance/references/security/sanitize-untrusted-html.md +105 -0
- package/skills/web-guidance/references/security/secure-external-subresources.md +202 -0
- package/skills/web-guidance/references/security/security.md +390 -0
- package/skills/web-guidance/references/security/trusted-types.md +141 -0
- package/skills/web-guidance/references/security/validate-origins.md +197 -0
- package/skills/web-guidance/references/security/verify-email-ownership.md +235 -0
- package/skills/web-guidance/references/ui-atoms/position-aware-tooltips.md +173 -0
- package/skills/web-guidance/references/ui-atoms/responsive-table.md +122 -0
- package/skills/web-guidance/references/ui-atoms/viewport-aware-dropdowns.md +178 -0
- package/skills/web-guidance/references/ui-behaviors/drag-and-drop.md +108 -0
- package/skills/web-guidance/references/ui-behaviors/light-dismiss-a-dialog.md +89 -0
- package/skills/web-guidance/references/ui-behaviors/motion.md +97 -0
- package/skills/web-guidance/references/ui-behaviors/platform-controls-dismiss-dialog.md +40 -0
- package/skills/web-guidance/references/ui-behaviors/prevent-page-scroll-under-modal-dialog.md +59 -0
- package/skills/web-guidance/references/ui-behaviors/search-hidden-content.md +141 -0
- package/skills/web-guidance/references/ui-behaviors/sortable-table.md +140 -0
- package/skills/web-guidance/references/ui-components/accordion.md +343 -0
- package/skills/web-guidance/references/ui-components/breadcrumbs.md +168 -0
- package/skills/web-guidance/references/ui-components/carousel.md +206 -0
- package/skills/web-guidance/references/ui-components/checkbox.md +144 -0
- package/skills/web-guidance/references/ui-components/dialog.md +218 -0
- package/skills/web-guidance/references/ui-components/hovercard.md +391 -0
- package/skills/web-guidance/references/ui-components/menu.md +415 -0
- package/skills/web-guidance/references/ui-components/navbar.md +281 -0
- package/skills/web-guidance/references/ui-components/navigation-drawer.md +429 -0
- package/skills/web-guidance/references/ui-components/persistent-toast-notifications.md +185 -0
- package/skills/web-guidance/references/ui-components/progress.md +181 -0
- package/skills/web-guidance/references/ui-components/spinner.md +179 -0
- package/skills/web-guidance/references/ui-components/tabs.md +371 -0
- package/skills/web-guidance/references/ui-components/toolbar.md +277 -0
- package/skills/web-guidance/references/user-experience/form-factor-adaptation.md +120 -0
- package/skills/web-guidance/references/user-experience/natural-interactions.md +155 -0
- package/skills/web-guidance/references/visual-design/color.md +43 -0
- package/skills/web-guidance/references/visual-design/dark-mode.md +350 -0
- package/dist/web/assets/AgentWork-C3KdZh5M.js +0 -2
- package/dist/web/assets/ApiTests-BLnl7JGO.js +0 -10
- package/dist/web/assets/Browse-C-Enjpmd.js +0 -2
- package/dist/web/assets/Chat-Bt6jZI68.js +0 -3
- package/dist/web/assets/Choices-D5eTFinz.js +0 -3
- package/dist/web/assets/CommandPalette-D89NM2_E.js +0 -1
- package/dist/web/assets/Compare-YfFYHwfK.js +0 -1
- package/dist/web/assets/Cost-ClaDz0YR.js +0 -1
- package/dist/web/assets/Data-jSFgAfej.js +0 -6
- package/dist/web/assets/Desktop-BofKeLVf.js +0 -1
- package/dist/web/assets/DesktopReview--WjeZh3w.js +0 -1
- package/dist/web/assets/Evidence-CJNzSQpY.js +0 -1
- package/dist/web/assets/Explore-BdFvqgF4.js +0 -2
- package/dist/web/assets/Features-CIBbw6PG.js +0 -1
- package/dist/web/assets/Flags-B62v4uWR.js +0 -2
- package/dist/web/assets/Flaky-Cut1kZw6.js +0 -1
- package/dist/web/assets/Impact-jOSl5Q0k.js +0 -3
- package/dist/web/assets/Jobs-DMJGgWtQ.js +0 -5
- package/dist/web/assets/KindPage-BbQWH5wa.js +0 -6
- package/dist/web/assets/Migration-BBgv7xXo.js +0 -2
- package/dist/web/assets/PageAgent-txbNoP6u.js +0 -1
- package/dist/web/assets/Product-BrXH81Ns.js +0 -7
- package/dist/web/assets/Production-CCVtFNGQ.js +0 -1
- package/dist/web/assets/Quality-Dxh-60A8.js +0 -1
- package/dist/web/assets/Readiness-DyJvSOLN.js +0 -1
- package/dist/web/assets/Record-Dnlkimjb.js +0 -1
- package/dist/web/assets/Regression-D2DDTwzs.js +0 -5
- package/dist/web/assets/Reports-ClcY7M0Q.js +0 -2
- package/dist/web/assets/Response-D9FYUvHg.js +0 -9
- package/dist/web/assets/RunDiff-CNImaEdz.js +0 -1
- package/dist/web/assets/Runs-CFvmdULI.js +0 -2
- package/dist/web/assets/Steps-BS66s0E1.js +0 -2
- package/dist/web/assets/TestCases-CrQEUtfD.js +0 -1
- package/dist/web/assets/TestData-e3IX0xwG.js +0 -2
- package/dist/web/assets/TestDebt-tXPoexMF.js +0 -1
- package/dist/web/assets/TestManagement-wjGaoZzI.js +0 -1
- package/dist/web/assets/Tosca-C5YaMLS0.js +0 -3
- package/dist/web/assets/WhatsNew-CwnRbDnd.js +0 -1
- package/dist/web/assets/azuredevops-BcQ5AFOM.js +0 -1
- package/dist/web/assets/crew-CWfjZIxE.js +0 -1
- package/dist/web/assets/families-DWilSDct.js +0 -1
- package/dist/web/assets/filters-CVzIOjPG.js +0 -1
- package/dist/web/assets/fold-tvLGnxD1.js +0 -1
- package/dist/web/assets/frame-Deu1IqzV.js +0 -13
- package/dist/web/assets/index-BWMIKyPB.js +0 -76
- package/dist/web/assets/index-C2Yq55oT.css +0 -2
- package/dist/web/assets/line-icons-C_amZ5-o.js +0 -1
- package/dist/web/assets/logos-C1NBtBMc.js +0 -1
- package/dist/web/assets/logos-DFyhMw0i.js +0 -1
- package/dist/web/assets/markdown-DC2HA0yZ.js +0 -10
- package/dist/web/assets/paletteCommands-Qxm5DZIs.js +0 -1
- package/dist/web/assets/parts-BR6dUwqn.js +0 -1
- package/dist/web/assets/productParts-BxdHuSBa.js +0 -1
- package/dist/web/assets/qualityParts-lz6eYVxC.js +0 -1
- package/dist/web/assets/recordTest-CcplpTS6.js +0 -1
- package/dist/web/assets/today-DuQFapJM.js +0 -1
- package/dist/web/assets/when-CHnpLdYw.js +0 -1
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Measure interaction and soft-navigation paint timing
|
|
2
|
+
|
|
3
|
+
Standard paint and responsiveness metrics leave a measurement gap after the initial page load:
|
|
4
|
+
|
|
5
|
+
- **`LargestContentfulPaint` (`largest-contentful-paint`)** only measures the initial ("hard") document load and stops emitting entries as soon as the user first interacts with the page.
|
|
6
|
+
- **`PerformanceEventTiming` and `event` / Interaction to Next Paint (INP)** measures input responsiveness up to the *very next frame* (such as a button active state or loading spinner), but does not track subsequent asynchronous paints—such as new content rendered after a `fetch()` resolves, or a client-side route transition completes.
|
|
7
|
+
- Observing route changes in a Single Page App (SPA) can be difficult outside of framework code. Just monitoring URL updates can over report URL changes that are not linked to route changes (for example, anchor link changes, multiple "redirects" for a single route change).
|
|
8
|
+
|
|
9
|
+
The `InteractionContentfulPaint` (`interaction-contentful-paint`) and `PerformanceSoftNavigation` (`soft-navigation`) performance entry types fill this gap. They propagate interaction causality across asynchronous tasks (`fetch`, `await`, `setTimeout`) to attribute new contentful paints and Single-Page Application (SPA) route transitions directly back to the user interaction that triggered them.
|
|
10
|
+
|
|
11
|
+
## How to implement
|
|
12
|
+
|
|
13
|
+
### 1. Observe contentful paints triggered by interactions
|
|
14
|
+
|
|
15
|
+
Use a `PerformanceObserver` with `type: 'interaction-contentful-paint'` and `buffered: true` to observe progressively larger contentful paints attributable to any user interaction.
|
|
16
|
+
|
|
17
|
+
Each `InteractionContentfulPaint` entry provides:
|
|
18
|
+
- `interactionId`: The unique identifier of the initiating user interaction (matching `PerformanceEventTiming.interactionId` and `PerformanceSoftNavigation.interactionId`).
|
|
19
|
+
- `startTime`: The timestamp when the initiating user interaction started, relative to the initial hard navigation time origin.
|
|
20
|
+
- `paintTime` and `presentationTime`: When the rendering phase ended and when the painted pixels were drawn on screen.
|
|
21
|
+
- `duration`: The elapsed time from interaction start to paint presentation (`presentationTime - startTime`).
|
|
22
|
+
- `largestContentfulPaint`: A snapshot `LargestContentfulPaint` object containing details about the largest painted element for that interaction so far (`element`, `size`, `url`, `id`, `renderTime`, `loadTime`).
|
|
23
|
+
|
|
24
|
+
```javascript
|
|
25
|
+
/**
|
|
26
|
+
* Observes contentful paints caused by user interactions and invokes a callback
|
|
27
|
+
* whenever an interaction produces a larger contentful paint.
|
|
28
|
+
*
|
|
29
|
+
* @param {(entry: PerformanceEntry) => void} onInteractionPaint
|
|
30
|
+
*/
|
|
31
|
+
export function observeInteractionPaints(onInteractionPaint) {
|
|
32
|
+
// Feature-detect support before calling observe() so unsupported browsers
|
|
33
|
+
// do not throw or log console warnings.
|
|
34
|
+
if (
|
|
35
|
+
typeof PerformanceObserver === 'undefined' ||
|
|
36
|
+
!PerformanceObserver.supportedEntryTypes?.includes('interaction-contentful-paint')
|
|
37
|
+
) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const observer = new PerformanceObserver((list) => {
|
|
42
|
+
for (const entry of list.getEntries()) {
|
|
43
|
+
// entry.duration is already calculated as (entry.presentationTime - entry.startTime),
|
|
44
|
+
// giving the total time from the user interaction to this contentful paint.
|
|
45
|
+
onInteractionPaint(entry);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// MANDATORY: Pass buffered: true to capture interaction paints that occurred
|
|
50
|
+
// before this observer was registered.
|
|
51
|
+
observer.observe({ type: 'interaction-contentful-paint', buffered: true });
|
|
52
|
+
return observer;
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### 2. Measure Largest Contentful Paint (LCP) for SPA soft navigations
|
|
57
|
+
|
|
58
|
+
A soft navigation is emitted by the browser when a trusted user interaction causes both a visible URL change and a contentful paint. To calculate LCP for each soft navigation:
|
|
59
|
+
|
|
60
|
+
1. Observe both `'soft-navigation'` and `'interaction-contentful-paint'` entries with `buffered: true`.
|
|
61
|
+
2. **MANDATORY:** When a `'soft-navigation'` entry is received, seed its initial LCP candidate by calling `softNavEntry.getLargestInteractionContentfulPaint()`. If the application painted content *before* updating the URL (for example, rendering a view and then calling `history.pushState()`), those early `interaction-contentful-paint` entries were emitted before the `soft-navigation` entry and still carry the *previous* `navigationId`.
|
|
62
|
+
3. **MANDATORY:** Correlate subsequent `'interaction-contentful-paint'` entries to the active soft navigation by matching `entry.interactionId === softNavEntry.interactionId`, **DO NOT** match by `entry.navigationId`. Using `interactionId` ensures you include paints that occurred before the URL update and exclude paints from later, unrelated interactions on the new route.
|
|
63
|
+
|
|
64
|
+
```javascript
|
|
65
|
+
/**
|
|
66
|
+
* Tracks FCP and LCP for each client-side soft navigation and reports finalized
|
|
67
|
+
* route metrics when the user navigates to a new route or hides the page.
|
|
68
|
+
*
|
|
69
|
+
* @param {(report: {
|
|
70
|
+
* url: string,
|
|
71
|
+
* navigationId: number,
|
|
72
|
+
* interactionId: number,
|
|
73
|
+
* fcpDuration: number,
|
|
74
|
+
* lcpDuration: number | null,
|
|
75
|
+
* lcpElement: Element | null,
|
|
76
|
+
* lcpSize: number | null
|
|
77
|
+
* }) => void} onSoftNavReport
|
|
78
|
+
*/
|
|
79
|
+
export function trackSoftNavigationLCP(onSoftNavReport) {
|
|
80
|
+
const supported =
|
|
81
|
+
typeof PerformanceObserver !== 'undefined' &&
|
|
82
|
+
PerformanceObserver.supportedEntryTypes?.includes('soft-navigation') &&
|
|
83
|
+
PerformanceObserver.supportedEntryTypes?.includes('interaction-contentful-paint');
|
|
84
|
+
|
|
85
|
+
if (!supported) {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let activeSoftNav = null;
|
|
90
|
+
let activeLcpEntry = null;
|
|
91
|
+
|
|
92
|
+
function finalizeCurrentSoftNav() {
|
|
93
|
+
if (!activeSoftNav) return;
|
|
94
|
+
|
|
95
|
+
onSoftNavReport({
|
|
96
|
+
// activeSoftNav.name holds the destination URL of the soft navigation.
|
|
97
|
+
url: activeSoftNav.name,
|
|
98
|
+
navigationId: activeSoftNav.navigationId,
|
|
99
|
+
interactionId: activeSoftNav.interactionId,
|
|
100
|
+
// activeSoftNav.duration is (activeSoftNav.presentationTime - activeSoftNav.startTime),
|
|
101
|
+
// which represents First Contentful Paint (FCP) relative to interaction start.
|
|
102
|
+
fcpDuration: activeSoftNav.duration,
|
|
103
|
+
// activeLcpEntry.duration is (activeLcpEntry.presentationTime - activeSoftNav.startTime),
|
|
104
|
+
// representing the soft navigation's LCP duration relative to interaction start.
|
|
105
|
+
lcpDuration: activeLcpEntry ? activeLcpEntry.duration : null,
|
|
106
|
+
lcpElement: activeLcpEntry?.largestContentfulPaint?.element ?? null,
|
|
107
|
+
lcpSize: activeLcpEntry?.largestContentfulPaint?.size ?? null,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
activeSoftNav = null;
|
|
111
|
+
activeLcpEntry = null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const softNavObserver = new PerformanceObserver((list) => {
|
|
115
|
+
for (const softNavEntry of list.getEntries()) {
|
|
116
|
+
// Finalize the previous route's metrics before resetting state for the new route.
|
|
117
|
+
finalizeCurrentSoftNav();
|
|
118
|
+
|
|
119
|
+
activeSoftNav = softNavEntry;
|
|
120
|
+
// MANDATORY: Seed the LCP candidate with getLargestInteractionContentfulPaint()
|
|
121
|
+
// to capture any attributed contentful paints that occurred before the URL updated.
|
|
122
|
+
activeLcpEntry = softNavEntry.getLargestInteractionContentfulPaint();
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
const icpObserver = new PerformanceObserver((list) => {
|
|
127
|
+
for (const icpEntry of list.getEntries()) {
|
|
128
|
+
// MANDATORY: Match by interactionId (not navigationId) so only paints caused
|
|
129
|
+
// by the soft navigation's initiating interaction update the route's LCP.
|
|
130
|
+
if (activeSoftNav && icpEntry.interactionId === activeSoftNav.interactionId) {
|
|
131
|
+
activeLcpEntry = icpEntry;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
softNavObserver.observe({ type: 'soft-navigation', buffered: true });
|
|
137
|
+
icpObserver.observe({ type: 'interaction-contentful-paint', buffered: true });
|
|
138
|
+
|
|
139
|
+
// Finalize the active route's LCP when the page is backgrounded or unloaded.
|
|
140
|
+
document.addEventListener('visibilitychange', () => {
|
|
141
|
+
if (document.visibilityState === 'hidden') {
|
|
142
|
+
finalizeCurrentSoftNav();
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
return { softNavObserver, icpObserver, finalizeCurrentSoftNav };
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### 3. Measure Core Web Vitals across soft navigations with `web-vitals`
|
|
151
|
+
|
|
152
|
+
If your goal is to report standard Core Web Vitals (LCP, CLS, and INP) across both hard and soft navigations to an analytics endpoint, use the `web-vitals` library (v6.0.0+) with `{ reportSoftNavs: true }` rather than manually slicing every metric timeline.
|
|
153
|
+
|
|
154
|
+
```javascript
|
|
155
|
+
import { onLCP, onFCP, onCLS, onINP } from 'web-vitals';
|
|
156
|
+
|
|
157
|
+
function sendToAnalytics(metric) {
|
|
158
|
+
// Example-only endpoint; replace with your real telemetry URL.
|
|
159
|
+
navigator.sendBeacon(
|
|
160
|
+
'/analytics',
|
|
161
|
+
JSON.stringify({
|
|
162
|
+
name: metric.name,
|
|
163
|
+
value: metric.value,
|
|
164
|
+
navigationType: metric.navigationType,
|
|
165
|
+
navigationURL: metric.navigationURL,
|
|
166
|
+
}),
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Pass { reportSoftNavs: true } to report metrics per soft navigation in addition
|
|
171
|
+
// to the initial hard navigation.
|
|
172
|
+
onLCP(sendToAnalytics, { reportSoftNavs: true });
|
|
173
|
+
onFCP(sendToAnalytics, { reportSoftNavs: true });
|
|
174
|
+
onCLS(sendToAnalytics, { reportSoftNavs: true });
|
|
175
|
+
onINP(sendToAnalytics, { reportSoftNavs: true });
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Best practices
|
|
179
|
+
|
|
180
|
+
- **DO** feature-detect `'interaction-contentful-paint'` and `'soft-navigation'` using `PerformanceObserver.supportedEntryTypes?.includes(...)` before calling `observer.observe()`.
|
|
181
|
+
- **DO** pass `{ buffered: true }` when observing `'interaction-contentful-paint'` and `'soft-navigation'` so early entries are not missed if analytics code initializes asynchronously.
|
|
182
|
+
- **DO** call `softNavEntry.getLargestInteractionContentfulPaint()` when handling a new `soft-navigation` entry so paints that occurred prior to the URL update are included in LCP.
|
|
183
|
+
- **DO** match `interaction-contentful-paint` entries to a soft navigation using `interactionId`, not `navigationId`.
|
|
184
|
+
- **DO** use `entry.duration` (or `entry.presentationTime - entry.startTime`) to measure interaction paint latency, rather than reporting `entry.presentationTime` directly. All `PerformanceEntry` timestamps are measured from the initial hard page load time origin, not from the soft navigation start.
|
|
185
|
+
- **DO NOT** rely on `performance.getEntriesByType('soft-navigation')` to monitor long-lived single-page applications, as the browser's buffer is limited to the first 50 soft navigation entries.
|
|
186
|
+
|
|
187
|
+
## Fallback strategies
|
|
188
|
+
|
|
189
|
+
Browser support for Interaction contentful paint performance entries: Limited availability.
|
|
190
|
+
Supported by: Chrome 151 (Jul 2026) and Edge 151 (Jul 2026).
|
|
191
|
+
Unsupported in: Firefox and Safari.
|
|
192
|
+
|
|
193
|
+
Browser support for Soft navigation performance entries: Limited availability.
|
|
194
|
+
Supported by: Chrome 151 (Jul 2026) and Edge 151 (Jul 2026).
|
|
195
|
+
Unsupported in: Firefox and Safari.
|
|
196
|
+
|
|
197
|
+
If your Baseline target includes browsers that do not support `InteractionContentfulPaint` or `PerformanceSoftNavigation`, treat these APIs as a progressive enhancement for Real User Monitoring (RUM):
|
|
198
|
+
|
|
199
|
+
1. **Feature detection and graceful degradation:** Guard observer registration with `PerformanceObserver.supportedEntryTypes?.includes('interaction-contentful-paint')` and `PerformanceObserver.supportedEntryTypes?.includes('soft-navigation')`. In browsers lacking support, skip registering the observers so your application runs without throwing errors.
|
|
200
|
+
2. **Keep standard hard-navigation observers active:** Continue observing standard `'largest-contentful-paint'`, `'event'`, and `'layout-shift'` entries across all browsers. Because `LargestContentfulPaint` is finalized on the first user interaction regardless of soft-navigation support, measuring soft navigations in supporting browsers does not alter or break initial hard-load LCP measurements.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Optimize image priority
|
|
2
|
+
|
|
3
|
+
Browsers use heuristics to assign loading priorities to images, but these defaults may not always align with your page's Largest Contentful Paint (LCP).
|
|
4
|
+
|
|
5
|
+
Using `fetchpriority` on an `<img>` element allows you to explicitly signal an image's importance to the browser, ensuring critical images load faster while non-essential ones don't compete for bandwidth.
|
|
6
|
+
|
|
7
|
+
The `loading=lazy` attribute prevents images from being downloaded at all when sufficiently off-screen which can further help prioritize images.
|
|
8
|
+
|
|
9
|
+
## How to implement
|
|
10
|
+
|
|
11
|
+
1. **Identify the LCP image**: Determine which image is the most likely candidate for the Largest Contentful Paint (usually the hero image at the top of the page).
|
|
12
|
+
2. **Elevate LCP priority**: Add `fetchpriority="high"` to the `<img>` element for the LCP candidate.
|
|
13
|
+
3. **Deprioritize non-critical images**: For images that are part of a secondary UI or are only revealed after user interaction (like mega menus, modals, or off-screen carousel slides), add `fetchpriority="low"`.
|
|
14
|
+
4. **Optimize lazy loading**: Never use `loading="lazy"` on the LCP image. For standard below-the-fold images, `loading="lazy"` is sufficient to defer the request until the user scrolls near them. Avoid adding `fetchpriority="low"` to these images, as you want them to load at normal priority once the user scrolls to them. Reserve `fetchpriority="low"` for images that are technically "above the fold" but not initially visible (e.g., hidden carousel slides or mega menus). For these hidden images, it is acceptable to use `loading="lazy"` as well; the browser will handle the request timing while respecting the low priority.
|
|
15
|
+
5. **Prefer default priorities**: If an image should have normal loading priority, omit the `fetchpriority` attribute entirely rather than setting it to `auto`. This is a stylistic convention to keep your HTML cleaner while relying on the browser's native heuristics.
|
|
16
|
+
|
|
17
|
+
## Example code
|
|
18
|
+
|
|
19
|
+
```html
|
|
20
|
+
<!-- Elevate priority for the LCP image -->
|
|
21
|
+
<img src="/images/hero-lcp.jpg"
|
|
22
|
+
alt="Main Banner"
|
|
23
|
+
fetchpriority="high"
|
|
24
|
+
width="800" height="400">
|
|
25
|
+
|
|
26
|
+
<!-- Deprioritize initially hidden images above the fold -->
|
|
27
|
+
<!-- Additionally use `loading="lazy"` if there are likely to be many images-->
|
|
28
|
+
<div class="carousel">
|
|
29
|
+
<img src="/images/gallery-alt.jpg"
|
|
30
|
+
alt="Gallery Image 1"
|
|
31
|
+
width="400" height="300">
|
|
32
|
+
<img src="/images/gallery-alt.jpg"
|
|
33
|
+
alt="Gallery Image 2"
|
|
34
|
+
fetchpriority="low"
|
|
35
|
+
loading="lazy"
|
|
36
|
+
width="400" height="300">
|
|
37
|
+
<div>
|
|
38
|
+
|
|
39
|
+
<!-- Deprioritize images revealed only after user interaction -->
|
|
40
|
+
<img src="/images/mega-menu-promo.jpg"
|
|
41
|
+
alt="Special Offer"
|
|
42
|
+
fetchpriority="low"
|
|
43
|
+
width="300" height="150">
|
|
44
|
+
|
|
45
|
+
<!-- Use lazy loading ALONE for standard below-the-fold images -->
|
|
46
|
+
<img src="/images/footer-logo.png"
|
|
47
|
+
alt="Footer Logo"
|
|
48
|
+
loading="lazy"
|
|
49
|
+
width="120" height="60">
|
|
50
|
+
|
|
51
|
+
<!-- Omit fetchpriority for images with standard priority -->
|
|
52
|
+
<img src="/images/standard-image.jpg"
|
|
53
|
+
alt="Standard Image"
|
|
54
|
+
width="400" height="300">
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Best practices
|
|
58
|
+
|
|
59
|
+
- **MANDATORY**: Always apply `fetchpriority="high"` to the LCP image.
|
|
60
|
+
- **MANDATORY**: Only use `fetchpriority="high"` on at most 1-2 critical images to avoid network contention and diluting the priority boost.
|
|
61
|
+
- **MANDATORY**: Use `fetchpriority="low"` for images that are technically "above the fold" but initially hidden (e.g., hidden carousel slides, mega menu images).
|
|
62
|
+
- **MANDATORY**: **Do not** use `fetchpriority="low"` on standard below-the-fold images that are already using `loading="lazy"`. These images should load at normal priority once they enter the viewport.
|
|
63
|
+
- **RECOMMENDED**: Avoid using `fetchpriority="auto"`. If you want the default priority, omit the attribute entirely to keep your HTML clean.
|
|
64
|
+
- **DO NOT** combine `fetchpriority="high"` with `loading="lazy"`.
|
|
65
|
+
- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority` and is not supported by any browser.
|
|
66
|
+
- **DO NOT** use the deprecated `loading="auto"` value. It was initially supported by Chrome but has been removed and is not supported by any browser.
|
|
67
|
+
|
|
68
|
+
## Fallback strategy
|
|
69
|
+
|
|
70
|
+
Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.
|
|
71
|
+
Supported by: Chrome 103 (Jun 2022), Edge 103 (Jun 2022), Firefox 132 (Oct 2024), and Safari 17.2 (Dec 2023).
|
|
72
|
+
|
|
73
|
+
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.
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
# Performance
|
|
2
|
+
|
|
3
|
+
## Critical Rendering Path (CRP) Optimization
|
|
4
|
+
|
|
5
|
+
The Critical Rendering Path dictates how quickly the browser converts HTML, CSS, and JavaScript into painted pixels.
|
|
6
|
+
|
|
7
|
+
### DOs
|
|
8
|
+
* **DO inline critical CSS**: Extract styles necessary for above-the-fold content and inject them directly into the HTML `<head>`. Defer the rest of the stylesheet.
|
|
9
|
+
* **DO use `async` or `defer` for all non-critical scripts**: Prevent JavaScript from blocking the DOM parser. Use `defer` for scripts that depend on the DOM or each other, and `async` for independent scripts. `type="module"` is preferred for modern JavaScript and is deferred by default so no need to have an explicit `defer` attribute but you can use `async` on independent module scripts.
|
|
10
|
+
* **DO split CSS by media queries**: Use the `media` attribute on `<link>` tags so the browser downloads unused stylesheets (e.g., print styles or desktop styles on mobile) without blocking the render.
|
|
11
|
+
* **DO utilize resource hints**: Add `preconnect` or `dns-prefetch` for essential third-party domains (e.g., font foundries or API endpoints) to establish early TLS handshakes.
|
|
12
|
+
|
|
13
|
+
### DON'Ts
|
|
14
|
+
* **DON'T use `@import` in CSS**: This creates sequential request chains that delay the CSS Object Model (CSSOM) construction.
|
|
15
|
+
* **DON'T place large, non-critical JavaScript in the `<head>`**: This halts DOM construction until the script is downloaded, parsed, and executed.
|
|
16
|
+
* **DON'T load invisible or unreachable CSS/JS**: Ensure build tools apply tree-shaking and CSS minification to drop unreachable code before deployment.
|
|
17
|
+
|
|
18
|
+
### Code Examples
|
|
19
|
+
|
|
20
|
+
**HTML: Deferring Non-Critical CSS & Scripts**
|
|
21
|
+
```html
|
|
22
|
+
<!-- Inline critical styles directly in head -->
|
|
23
|
+
<style>
|
|
24
|
+
body { margin: 0; font-family: system-ui; }
|
|
25
|
+
.hero { min-height: 100vh; }
|
|
26
|
+
</style>
|
|
27
|
+
|
|
28
|
+
<!-- Defer non-critical CSS -->
|
|
29
|
+
<link rel="preload" href="non-critical.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
|
|
30
|
+
<noscript><link rel="stylesheet" href="non-critical.css"></noscript>
|
|
31
|
+
|
|
32
|
+
<!-- Load CSS conditionally based on viewport -->
|
|
33
|
+
<link rel="stylesheet" href="mobile.css" media="(max-width: 768px)">
|
|
34
|
+
|
|
35
|
+
<!-- Defer JavaScript execution -->
|
|
36
|
+
<script defer src="app-bundle.js"></script>
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### The Resource Hint Navigator
|
|
40
|
+
|
|
41
|
+
| Hint | Tool Use Case | Example |
|
|
42
|
+
| :--- | :--- | :--- |
|
|
43
|
+
| `preconnect` | Resolve TLS/DNS for known third-party APIs | API endpoints, font services |
|
|
44
|
+
| `dns-prefetch` | Lean fallback for non-critical third-party origins | Ad servers, analytics fallbacks |
|
|
45
|
+
| `preload` | Same-origin asset needed *now* for rendering | Hero images, render-blocking fonts |
|
|
46
|
+
| `prefetch` | Assets needed for next-page navigation | Next-page bundle, detail views |
|
|
47
|
+
|
|
48
|
+
**Single-Sentence Mental Model**: "Preconnect for domains, Preload for viewport, Prefetch for futures."
|
|
49
|
+
|
|
50
|
+
## Largest Contentful Paint (LCP) & Resource Fetching
|
|
51
|
+
|
|
52
|
+
LCP measures the time required to render the largest visible text or image block within the viewport. Optimize LCP by prioritizing visible elements and prepolishing.
|
|
53
|
+
|
|
54
|
+
### DOs
|
|
55
|
+
* **DO declare the LCP image in standard HTML**: Ensure LCP images are present in the raw HTML response so the preload scanner discovers it immediately. This can be via an `<img>` element (preferred) or a `<link rel="preload" as="image">` (where the image resource is loaded due to JavaScript or CSS). Avoid relying on JavaScript or CSS to be the only source of the image resource.
|
|
56
|
+
* **DO use `fetchpriority="high"` on the LCP images**: Images are not downloaded initially while the browser prioritizes render-blocking resources like CSS and JavaScript and can perform layout to discover if the images are in the viewport or not. Use `fetchpriority="high"` to signal to the browser's heuristic engine to start downloading the LCP image earlier. This should be on the `<img>` element (`<img fetchpriority="high">`) and any preload (`<link rel="preload" as="image" fetchpriority="high">`).
|
|
57
|
+
* **DO use `fetchpriority="low"` to demote competing elements that are not in the initial viewport**: Lower the priority of large images or carousels that are *not* the primary LCP element and do *not* appear in the initial viewport, but may still be downloaded if near the viewport or hidden with CSS (for example `overflow:scroll` for carousels). Images with `fetchpriority="low"` will still be downloaded but start after higher-priority resources the browser has queued.
|
|
58
|
+
* **DO use `loading="lazy"` to avoid loading competing elements that are far out of the initial viewport**: Images, iframes, and video and audio media which are well outside of the viewport should be lazy-loaded to avoid fetching these at all. Images with `loading="lazy"` will not be downloaded at all when well outside the viewport but will download when in, or near, the viewport (depending on browser heuristics and connection settings),.
|
|
59
|
+
|
|
60
|
+
### DON'Ts
|
|
61
|
+
* **DON'T lazy-load the LCP image**: Never apply `loading="lazy"` to above-the-fold images. This purposefully delays the fetch until layout calculation is complete, severely degrading LCP.
|
|
62
|
+
* **DON'T overuse `fetchpriority="high"`**: Prioritization is a zero-sum mechanism. Elevating too many resources creates network contention and negates the benefit.
|
|
63
|
+
* **DON'T implement complex JavaScript loaders for the hero section**: Client-side rendering of the LCP element introduces substantial request chains (HTML -> JS -> Execution -> Image Request).
|
|
64
|
+
|
|
65
|
+
### Code Examples
|
|
66
|
+
|
|
67
|
+
**HTML: LCP Image Optimization**
|
|
68
|
+
```html
|
|
69
|
+
<!-- Standard LCP Image -->
|
|
70
|
+
<img
|
|
71
|
+
src="/images/hero.webp"
|
|
72
|
+
alt="Hero Product"
|
|
73
|
+
fetchpriority="high"
|
|
74
|
+
width="1200"
|
|
75
|
+
height="600"
|
|
76
|
+
>
|
|
77
|
+
|
|
78
|
+
<!-- Preloading a CSS-based LCP background -->
|
|
79
|
+
<link rel="preload" as="image" href="/images/bg-hero.webp" fetchpriority="high" type="image/webp">
|
|
80
|
+
|
|
81
|
+
<!-- Demoting an offscreen non-LCP carousel image -->
|
|
82
|
+
<img src="/images/carousel-2.webp" fetchpriority="low" loading="lazy" alt="Slide 2">
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Interaction to Next Paint (INP) & Main Thread Unblocking
|
|
86
|
+
|
|
87
|
+
INP measures the latency of all interactive events across the page's lifecycle. Poor INP is caused by long-running JavaScript tasks blocking the main thread.
|
|
88
|
+
|
|
89
|
+
### DOs
|
|
90
|
+
* **DO break up long tasks**: Any JavaScript execution exceeding 50ms should be split. Yield to the main thread frequently so the browser can process pending user inputs.
|
|
91
|
+
* **DO use `scheduler.yield()` with a fallback**: Utilize the modern `scheduler.yield()` API to place task continuations at the *front* of the queue, falling back to `setTimeout` wrapped in a Promise for unsupported browsers.
|
|
92
|
+
* **DO debounce or throttle rapid event listeners**: Limit the execution frequency of handlers attached to `scroll`, `resize`, or rapid `input` events.
|
|
93
|
+
* **DO separate UI updates from heavy computations**: Update the UI synchronously to provide immediate visual feedback, then push background processing to a Web Worker or deferred task.
|
|
94
|
+
|
|
95
|
+
### DON'Ts
|
|
96
|
+
* **DON'T rely solely on `setTimeout(..., 0)` for continuous yielding**: Standard `setTimeout` places continuations at the *back* of the task queue, potentially causing long delays if other tasks are pending. Use `scheduler.yield()` where available.
|
|
97
|
+
* **DON'T cause layout thrashing**: Avoid interleaving DOM reads (`offsetHeight`, `getBoundingClientRect`) and writes (`style.height`) within the same loop. Batch DOM reads, then batch DOM writes.
|
|
98
|
+
* **DON'T block the thread with recurring timers**: Avoid heavy polling with `setInterval` that starves the main thread.
|
|
99
|
+
|
|
100
|
+
### Code Examples
|
|
101
|
+
|
|
102
|
+
**JS: `scheduler.yield` Polyfill and Usage**
|
|
103
|
+
```javascript
|
|
104
|
+
// Polyfill for yielding to main thread
|
|
105
|
+
async function yieldToMain() {
|
|
106
|
+
if ('scheduler' in window && 'yield' in scheduler) {
|
|
107
|
+
return await scheduler.yield();
|
|
108
|
+
}
|
|
109
|
+
return new Promise(resolve => setTimeout(resolve, 0));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Processing a large array without blocking user input
|
|
113
|
+
async function processLargeList(items) {
|
|
114
|
+
for (let i = 0; i < items.length; i++) {
|
|
115
|
+
processItem(items[i]);
|
|
116
|
+
|
|
117
|
+
// Yield every 50 iterations to allow rendering/interaction
|
|
118
|
+
if (i % 50 === 0) {
|
|
119
|
+
await yieldToMain();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Main Thread Task Slicing Heuristic
|
|
126
|
+
|
|
127
|
+
**The 50ms Rule for INP**:
|
|
128
|
+
- **< 50ms**: Execute synchronously.
|
|
129
|
+
- **50ms - 250ms**: Slice tasks and yield with `scheduler.yield()`.
|
|
130
|
+
- **> 250ms**: Offload to a Web Worker.
|
|
131
|
+
|
|
132
|
+
## Third-Party Script Management
|
|
133
|
+
|
|
134
|
+
Third-party scripts (analytics, ads, chat widgets) are the primary source of main thread congestion.
|
|
135
|
+
|
|
136
|
+
### DOs
|
|
137
|
+
* **DO avoid third-party scripts blocking main content**: Use `defer` with all third-party scripts unless critical to the page load and load them in the footer of the page, rather than the `<head>`.
|
|
138
|
+
* **DO self-host critical third-party dependencies**: Reduce DNS lookups and enforce custom `Cache-Control` logic by hosting third-party libraries on the origin domain.
|
|
139
|
+
|
|
140
|
+
### Code Examples
|
|
141
|
+
|
|
142
|
+
**HTML: Third-Party Script Execution**
|
|
143
|
+
```html
|
|
144
|
+
<!-- 1. Place third-party scripts near the end of the page with the defer attribute -->
|
|
145
|
+
<script defer src="https://www.example.com/third-party.js"></script>
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## CSS Rendering & Containment Optimization
|
|
149
|
+
|
|
150
|
+
Rendering involves Layout, Style, Paint, and Compositing calculations. CSS Containment limits the scope of these calculations which is useful on large, complex pages where such calculations can cause performance problems.
|
|
151
|
+
|
|
152
|
+
### DOs
|
|
153
|
+
* **DO use `content-visibility: auto` on off-screen sections on large, complex pages**: Instruct the browser to skip layout and paint calculations for entire subtrees until they approach the viewport.
|
|
154
|
+
* **DO pair `content-visibility` with `contain-intrinsic-size`**: Prevent layout shifts and scrollbar jumping by providing a placeholder height/width for unrendered containers.
|
|
155
|
+
* **DO derive `contain-intrinsic-size` from the content**: When setting `contain-intrinsic-size` use the `auto` keyword and a value that's derived from what is known about the contents (i.e. text size, spacing, size of graphics, character count). Preferably use units such as `rem`, `lh`, `cap`, or `ch` that match values used for the elements within the contents rather than `px`. If the content for items in a group is not consistently sized, then use an average size.
|
|
156
|
+
* **DO apply explicit CSS containment (`contain`)**: For isolated UI components (like modals or widgets), use `contain: layout style paint` to prevent internal changes from triggering page-wide reflows.
|
|
157
|
+
|
|
158
|
+
### DON'Ts
|
|
159
|
+
* **DON'T apply `content-visibility: auto` on smaller, simpler pages**: The gains will be negligible and there are risks of side effects with content jumping.
|
|
160
|
+
* **DON'T apply `content-visibility: auto` to above-the-fold content**: The browser will still evaluate it, but forcing it through the containment engine unnecessarily adds slight overhead to visible elements.
|
|
161
|
+
* **DON'T overuse `will-change` globally**: Indiscriminately applying `will-change: transform` to multiple elements consumes excessive VRAM, causing GPU crashes or sluggish rendering.
|
|
162
|
+
* **DON'T forget accessibility when hiding elements**: `content-visibility: auto` keeps elements in the DOM for screen readers. If content should be truly hidden from assistive technology when off-screen, manage `aria-hidden` attributes manually.
|
|
163
|
+
|
|
164
|
+
### Code Examples
|
|
165
|
+
|
|
166
|
+
**CSS: Content Visibility and Containment**
|
|
167
|
+
```css
|
|
168
|
+
/* Optimize a long list of articles below the fold */
|
|
169
|
+
.article-list-item {
|
|
170
|
+
content-visibility: auto;
|
|
171
|
+
contain-intrinsic-size: auto 600px; /* Provides a 600px placeholder */
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
.row {
|
|
175
|
+
--row-gap: .4rem;
|
|
176
|
+
--title-height: 1lh;
|
|
177
|
+
--description-height: 0.85lh;
|
|
178
|
+
|
|
179
|
+
display: grid;
|
|
180
|
+
row-gap: var(--row-gap);
|
|
181
|
+
content-visibility: auto;
|
|
182
|
+
/* The sum of the title height, row gap, and description height should be the size of the contents when skipped for rendering. */
|
|
183
|
+
contain-intrinsic-block-size: auto calc(var(--title-height) + var(--row-gap) + var(--description-height));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/* Scope a complex widget to prevent layout thrashing */
|
|
187
|
+
.isolated-widget {
|
|
188
|
+
contain: layout style paint;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/* Hardware accelerate an animation only on hover */
|
|
192
|
+
.interactive-button:hover {
|
|
193
|
+
will-change: transform;
|
|
194
|
+
transform: scale(1.05);
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Modern Image & Media Optimization
|
|
199
|
+
|
|
200
|
+
Images typically represent the largest payload on a given web page. Optimization requires format negotiation, responsive sizing, and layout stabilization.
|
|
201
|
+
|
|
202
|
+
### DOs
|
|
203
|
+
* **DO serve modern formats (AVIF / WebP / JPEG XL)**: Use the `<picture>` element to offer AVIF or JPEG XL (best compression), falling back to WebP, and finally JPEG/PNG for legacy browsers.
|
|
204
|
+
* **DO apply explicit `width` and `height` attributes**: Setting native attributes allows the browser to compute the aspect ratio immediately, reserving space and eliminating CLS. Image dimensions may be set either as HTML attributes or CSS properties.
|
|
205
|
+
* **DO utilize `loading="lazy"` on all below-the-fold images**: Utilize native browser lazy loading to defer network requests for images outside the initial viewport.
|
|
206
|
+
* **DO implement responsive images with `srcset` and `sizes`**: Serve tailored resolutions based on screen density and viewport width to prevent mobile devices from downloading desktop-sized images.
|
|
207
|
+
|
|
208
|
+
### DON'Ts
|
|
209
|
+
* **DON'T lazy load above-the-fold images**: This directly harms LCP. Visible images must use `loading="eager"` (the default).
|
|
210
|
+
* **DON'T delete necessary dimensions**: Failing to specify width/height on lazy loaded images causes layout shifts.
|
|
211
|
+
* **DON'T omit the `sizes` attribute when using `srcset`**: Without `sizes`, the browser assumes `100vw` and downloads the largest available image.
|
|
212
|
+
|
|
213
|
+
### Code Examples
|
|
214
|
+
|
|
215
|
+
**HTML: Comprehensive Responsive Image Component**
|
|
216
|
+
```html
|
|
217
|
+
<picture>
|
|
218
|
+
<!-- Modern Formats with Source Negotiation -->
|
|
219
|
+
<source type="image/avif" srcset="hero-400w.avif 400w, hero-800w.avif 800w" sizes="(max-width: 600px) 100vw, 50vw">
|
|
220
|
+
<source type="image/webp" srcset="hero-400w.webp 400w, hero-800w.webp 800w" sizes="(max-width: 600px) 100vw, 50vw">
|
|
221
|
+
|
|
222
|
+
<!-- Fallback + Dimensions + Priority for Above-The-Fold -->
|
|
223
|
+
<img
|
|
224
|
+
src="hero-800w.jpg"
|
|
225
|
+
alt="Descriptive text"
|
|
226
|
+
width="800"
|
|
227
|
+
height="600"
|
|
228
|
+
fetchpriority="high"
|
|
229
|
+
loading="eager"
|
|
230
|
+
>
|
|
231
|
+
</picture>
|
|
232
|
+
|
|
233
|
+
<!-- Below-The-Fold Image -->
|
|
234
|
+
<img
|
|
235
|
+
src="footer-icon.png"
|
|
236
|
+
alt="Footer Logo"
|
|
237
|
+
width="100"
|
|
238
|
+
height="100"
|
|
239
|
+
loading="lazy"
|
|
240
|
+
>
|
|
241
|
+
|
|
242
|
+
<!-- DO: Use native lazy loading for below the fold iframes -->
|
|
243
|
+
<iframe src="https://example.com/map" width="800" height="600" loading="lazy" title="Example Map"></iframe>
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## Service Workers & Caching Strategies
|
|
247
|
+
|
|
248
|
+
Client-side caching via Service Workers allows applications to bypass the network entirely, serving resources from disk/memory.
|
|
249
|
+
|
|
250
|
+
### DOs
|
|
251
|
+
* **DO use a `CacheFirst` strategy for static, versioned assets**: Immutable files (fonts, JS/CSS bundles with hash strings) should be served directly from the cache to guarantee instant loading.
|
|
252
|
+
* **DO use `StaleWhileRevalidate` for dynamic, non-critical resources**: For API calls where slight staleness is acceptable, serve immediately from cache while silently updating the cache in the background.
|
|
253
|
+
* **DO implement a `NetworkFirst` strategy for HTML documents**: Ensure the user always receives the latest application shell and manifest, falling back to cache only if offline.
|
|
254
|
+
* **DO restrict cache sizes and expiry**: Use expiration plugins to prevent the Service Worker from exhausting the device's storage quota.
|
|
255
|
+
|
|
256
|
+
### DON'Ts
|
|
257
|
+
* **DON'T cache opaque responses blindly**: Responses from third-party domains lacking CORS headers are "opaque". Caching them heavily consumes quota and fails silently. Only cache them using `NetworkFirst` or `StaleWhileRevalidate`.
|
|
258
|
+
* **DON'T cache POST requests**: Service workers cannot cache non-GET requests natively. Implement background sync queues for offline submissions.
|
|
259
|
+
* **DON'T bypass versioning**: Failing to update asset hashes/versions will trap users in infinite cache loops.
|
|
260
|
+
* **DON'T use `Cache-Control: no-store` for non-sensitive resources**: This directive prevents the browser from storing the page in the **Back-Forward Cache (bfcache)**, leading to significantly slower perceived performance. Use it only for truly private data, and use `Cache-Control: no-cache` or `Cache-Control: max-age=0` for pages that simply need to serve up-to-date content.
|
|
261
|
+
|
|
262
|
+
### Code Examples
|
|
263
|
+
|
|
264
|
+
**JS: Service Worker Caching via Workbox**
|
|
265
|
+
```javascript
|
|
266
|
+
import { registerRoute } from 'workbox-routing';
|
|
267
|
+
import { CacheFirst, StaleWhileRevalidate, NetworkFirst } from 'workbox-strategies';
|
|
268
|
+
import { ExpirationPlugin } from 'workbox-expiration';
|
|
269
|
+
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
|
|
270
|
+
|
|
271
|
+
// 1. HTML Documents: Network First
|
|
272
|
+
registerRoute(
|
|
273
|
+
({ request }) => request.mode === 'navigate',
|
|
274
|
+
new NetworkFirst({ cacheName: 'pages-cache' })
|
|
275
|
+
);
|
|
276
|
+
|
|
277
|
+
// 2. Static Assets (JS, CSS, Fonts): Cache First
|
|
278
|
+
registerRoute(
|
|
279
|
+
({ request }) => ['style', 'script', 'font'].includes(request.destination),
|
|
280
|
+
new CacheFirst({
|
|
281
|
+
cacheName: 'static-resources',
|
|
282
|
+
plugins: [
|
|
283
|
+
new CacheableResponsePlugin({ statuses: [0, 200] }),
|
|
284
|
+
new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 30 * 24 * 60 * 60 })
|
|
285
|
+
]
|
|
286
|
+
})
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
// 3. API Responses: Stale While Revalidate
|
|
290
|
+
registerRoute(
|
|
291
|
+
({ url }) => url.pathname.startsWith('/api/v1/content'),
|
|
292
|
+
new StaleWhileRevalidate({
|
|
293
|
+
cacheName: 'api-cache',
|
|
294
|
+
plugins: [
|
|
295
|
+
new CacheableResponsePlugin({ statuses: [0, 200] })
|
|
296
|
+
]
|
|
297
|
+
})
|
|
298
|
+
);
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
## Web Fonts Optimization
|
|
302
|
+
|
|
303
|
+
Web fonts are a common source of render blocking. Optimizing them reduces the Flash of Invisible Text (FOIT) and speeds up initial rendering.
|
|
304
|
+
|
|
305
|
+
### DOs
|
|
306
|
+
* **DO preload critical fonts**: Use `<link rel="preload" as="font" type="font/woff2" crossorigin>` for fonts seen above the fold. Do include the `crossorigin` attribute for all fonts (even same origin fonts).
|
|
307
|
+
* **DO subset fonts**: Trim font weights and glyph variations to include only the characters your application requires.
|
|
308
|
+
|
|
309
|
+
### DON'Ts
|
|
310
|
+
* **DON'T preload all fonts**: Over-preloading leads to network contention that starves other critical assets.
|
|
311
|
+
* **DON'T use `fetchpriority="high"` on fonts**: Fonts are loaded with a high priority by default so there is no need to specify `fetchpriority="high"`.
|
|
312
|
+
|
|
313
|
+
### Code Examples
|
|
314
|
+
|
|
315
|
+
**CSS: Font Loading Face**
|
|
316
|
+
```css
|
|
317
|
+
@font-face {
|
|
318
|
+
font-family: 'Modern Sans';
|
|
319
|
+
src: url('/fonts/modern-sans.woff2') format('woff2');
|
|
320
|
+
}
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
**HTML: Critical Font Preload**
|
|
324
|
+
```html
|
|
325
|
+
<!-- Always use crossorigin for fonts even if on the same origin -->
|
|
326
|
+
<link rel="preload" href="/fonts/modern-sans.woff2" as="font" type="font/woff2" crossorigin>
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
## Video Performance & Metrics
|
|
330
|
+
|
|
331
|
+
Video payloads are among the heaviest assets. Optimization focuses on reducing bandwidth stall and preserving Cumulative Layout Shift (CLS) stability.
|
|
332
|
+
|
|
333
|
+
### DOs
|
|
334
|
+
* **DO specify explicit `width` and `height` attributes**: Setting native dimensions reserves layout space and prevents CLS.
|
|
335
|
+
* **DO provide a `poster` image fallback**: Display a lightweight image placeholder while the video buffers to improve perceived performance.
|
|
336
|
+
* **DO use `<link rel="preload" as="image" fetchpriority="high">` for poster images where the video is the LCP element**: This ensures the image is downloaded as quickly as possible.
|
|
337
|
+
* **DO use `preload="none"` for non-critical videos**: Delay bandwidth consumption for below-the-fold or non-autoplaying videos.
|
|
338
|
+
* **DO serve modern formats via source negotiation**: Offer WebM (better compression ratio) alongside standard MP4 formats.
|
|
339
|
+
* **DO use `loading="lazy"` for offscreen videos**: Lazy-loading videos allow `poster` and `preload` downloads to be deferred until the video is in or near the viewport.
|
|
340
|
+
|
|
341
|
+
### DON'Ts
|
|
342
|
+
* **DON'T auto-play video files blindly**: Rely on user intent or use progressive enhancement streams.
|
|
343
|
+
* **DON'T auto-play large video files at all**: Rely on user intent before downloading large files.
|
|
344
|
+
|
|
345
|
+
### Code Examples
|
|
346
|
+
|
|
347
|
+
**HTML: Accessible and Dynamic Video Loader**
|
|
348
|
+
```html
|
|
349
|
+
<video
|
|
350
|
+
controls
|
|
351
|
+
width="1200"
|
|
352
|
+
height="675"
|
|
353
|
+
poster="/images/video-poster.webp"
|
|
354
|
+
preload="none"
|
|
355
|
+
loading="lazy"
|
|
356
|
+
>
|
|
357
|
+
<source src="/videos/intro.webm" type="video/webm">
|
|
358
|
+
<source src="/videos/intro.mp4" type="video/mp4">
|
|
359
|
+
<!-- Include accessibility tracks -->
|
|
360
|
+
<track src="/video-caps.vtt" kind="captions" srclang="en" label="English">
|
|
361
|
+
</video>
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
## JavaScript Code-Splitting
|
|
365
|
+
|
|
366
|
+
Heavy monolithic bundles block main thread parse times on low-end devices. Splitting ensures we only download bytes required for the immediate viewport.
|
|
367
|
+
|
|
368
|
+
### DOs
|
|
369
|
+
* **DO use dynamic imports**: Split routes or heavy UI libraries using standard `import()` specifications.
|
|
370
|
+
* **DO configure bundler asset chunking**: Use Vite or Webpack rollup directives to split third-party vendors from runtime application logic.
|
|
371
|
+
|
|
372
|
+
### DON'Ts
|
|
373
|
+
* **DON'T ship a single, enormous `app.js` bundle**: It increases parse time and memory consumption for initial views.
|
|
374
|
+
|
|
375
|
+
### Code Examples
|
|
376
|
+
|
|
377
|
+
**JS: Route based Dynamic Splitting**
|
|
378
|
+
```javascript
|
|
379
|
+
// Dynamic import of heavy module only when button is clicked
|
|
380
|
+
document.getElementById('heavy-btn').addEventListener('click', async () => {
|
|
381
|
+
const { heavyFunction } = await import('./heavy-module.js');
|
|
382
|
+
heavyFunction();
|
|
383
|
+
});
|
|
384
|
+
```
|