Skip to content

Add Mermaid diagrams and real-world examples for script loading validation#56

Merged
nucliweb merged 7 commits into
mainfrom
snippet/Prefetch-Resource-Validation
Feb 12, 2026
Merged

Add Mermaid diagrams and real-world examples for script loading validation#56
nucliweb merged 7 commits into
mainfrom
snippet/Prefetch-Resource-Validation

Conversation

@nucliweb

Copy link
Copy Markdown
Owner
  • Add comprehensive Mermaid diagrams to Prefetch-Resource-Validation:

    • Visual comparison of preload vs prefetch lifecycle
    • Decision tree for choosing resource hints
    • Page load timeline showing prefetch impact
    • Adaptive prefetch strategy based on connection
    • Resource lifecycle state diagram
  • Document real-world consent script scenario in Validate-Preload-Async-Defer-Scripts:

    • Explain why fetchpriority="high" doesn't solve the problem
    • Show diagrams comparing different approaches
    • Provide decision tree for consent script loading
    • Add priority comparison table
    • Reference future blog post on server-side conditional loading
  • Replace complex diagram with clear scenario table for better readability

  • Add LinkedIn discussion context about third-party consent scripts

Visual improvements make it easier to understand:

  • When to use preload vs prefetch
  • How resource hints affect page load performance
  • Optimal strategies for different connection types
  • Real-world tradeoffs for consent management scripts

…ation

- Add comprehensive Mermaid diagrams to Prefetch-Resource-Validation:
  * Visual comparison of preload vs prefetch lifecycle
  * Decision tree for choosing resource hints
  * Page load timeline showing prefetch impact
  * Adaptive prefetch strategy based on connection
  * Resource lifecycle state diagram

- Document real-world consent script scenario in Validate-Preload-Async-Defer-Scripts:
  * Explain why fetchpriority="high" doesn't solve the problem
  * Show diagrams comparing different approaches
  * Provide decision tree for consent script loading
  * Add priority comparison table
  * Reference future blog post on server-side conditional loading

- Replace complex diagram with clear scenario table for better readability
- Add LinkedIn discussion context about third-party consent scripts

Visual improvements make it easier to understand:
- When to use preload vs prefetch
- How resource hints affect page load performance
- Optimal strategies for different connection types
- Real-world tradeoffs for consent management scripts
@vercel

vercel Bot commented Feb 12, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
webperf-snippets Ready Ready Preview, Comment Feb 12, 2026 4:10pm
webperf-snippets-u6am Ready Ready Preview, Comment Feb 12, 2026 4:10pm

@claude

claude Bot commented Feb 12, 2026

Copy link
Copy Markdown

PR Review: Add Mermaid diagrams and real-world examples

Great additions overall! The Mermaid diagrams significantly improve comprehension, and the real-world consent script case study is highly practical. Here are my observations:


New File: Prefetch-Resource-Validation.mdx

Strengths:

  • The snippet is well-structured with clear separation of concerns (thresholds, analysis, reporting)
  • Graceful handling of the no-prefetch-hints edge case
  • Good use of console.group/console.table for organized DevTools output
  • Framework-specific guidance (Next.js, Remix, SvelteKit) adds real practical value
  • The Mermaid state diagram for the resource lifecycle is an excellent visual aid

Issues to address:

  1. Inaccurate "loaded" count in summary — The summary logs issues.length + validPrefetch.length as "Loaded resources", but issues also includes resources with only an info-severity "not-loaded" warning — those have not actually loaded. Consider counting only resources where analysis.loaded === true.

  2. Cache status heuristic unreliable for cross-origin resourcestransferSize === 0 indicates a cache hit for same-origin resources, but for cross-origin resources (common with CDN-hosted prefetch targets) this value is always 0 due to the Timing-Allow-Origin restriction. Worth noting this limitation, or omitting the cache status for cross-origin entries.

  3. isCurrentPage check has a fragile timing assumption — The entry.startTime < 5000 heuristic can misclassify a slow-loading current-page resource that takes more than 5s. A more reliable signal might be checking initiatorType !== 'link' alone, or matching against known initiator types like 'script', 'css', 'img'.

  4. Missing as attribute not flagged — If a prefetch link is missing the as attribute, link.getAttribute("as") returns null and the fallback is "unknown". The inappropriateTypes object has no unknown key, so this silently passes without warning. A missing as attribute is worth flagging — the browser cannot do proper cache matching without knowing the resource type.

  5. "Not loaded" items inflate issue totals — The final summary includes info-level "not loaded" items in the issue count. A resource that simply has not loaded yet (e.g., the page was just opened) is not really an issue and can produce confusing output.


Modified File: Validate-Preload-Async-Defer-Scripts.mdx

Strengths:

  • The consent script real-world case study is excellent — this is a very common anti-pattern and the clear explanation of why fetchpriority="high" does not help is genuinely valuable
  • The priority comparison table is clean and immediately actionable
  • Cosmetic whitespace and quote-style fixes improve code consistency

Minor issues:

  1. Placeholder link — The "coming soon" blog reference links to #. Consider removing the hyperlink wrapper until the article is published to avoid a broken anchor, e.g. change it to plain text: _(coming soon on joanleon.dev)_

  2. Solution 1 Mermaid diagram omits the key attribute — The diagram for Solution 1 does not explicitly call out fetchpriority="low" prominently. Minor, but aligning the diagram with the code example would strengthen the explanation.


General Notes

  • Mermaid rendering: Nextra does not enable Mermaid out of the box in all versions. Worth verifying the diagrams actually render in the Vercel deploy preview before merging — they will display as raw fenced code blocks if the integration is not configured.
  • No tests required — Per CLAUDE.md, there are no configured tests.
  • The _meta.json update is correct — the new page is properly registered.

Priority fixes before merging:

  1. Fix the "loaded" resource count in the summary (bug — misleading output)
  2. Remove the placeholder [...](#) link or convert it to plain text

The summary was counting all resources (issues + validPrefetch) as 'loaded',
but resources with 'not-loaded' warnings were incorrectly included.

Now correctly filters and counts only resources where loaded: true.

Before: counted resources that failed or haven't loaded yet
After: accurate count of actually loaded prefetch resources
@claude

claude Bot commented Feb 12, 2026

Copy link
Copy Markdown

PR Review: Add Mermaid diagrams and real-world examples for script loading validation

Overall this is a high-quality, well-structured contribution that adds significant educational value to the documentation. The new Prefetch-Resource-Validation snippet is thorough and the Mermaid diagrams effectively communicate concepts that are hard to explain in plain text. Below are specific observations.


Prefetch Resource Validation (new file)

Strengths

  • The JavaScript snippet is well-structured with an IIFE, clear threshold constants, and grouped console output — consistent with the existing snippet style.
  • Good use of performance.getEntriesByType('resource') for real size/cache data rather than just inspecting the DOM.
  • URL normalisation via new URL(entry.name, location.origin) is a nice touch that avoids false negatives from relative vs. absolute comparisons.
  • The Mermaid diagrams, tables, and framework-specific examples (Next.js, Remix, SvelteKit) add clear practical value.

Issues / Suggestions

  1. analysis.duration is set but never displayed.
    The duration field is stored in the analysis object (line ~130) but is never surfaced in any of the console tables. Either remove it or add it to the output so readers can see actual download times.

  2. Cache status false-positive for opaque responses.
    transferSize === 0 is used to detect 'cached', but the spec also returns 0 for cross-origin resources served without Timing-Allow-Origin. Consider falling back to checking encodedBodySize > 0 && transferSize === 0 as a softer signal, or noting the limitation in a comment.

  3. isCurrentPage check uses a hard-coded 5-second cutoff.
    entry.startTime < 5000 is a heuristic that will flag resources on very slow pages incorrectly. A brief comment explaining why 5 s was chosen (e.g., well before TTI on most pages) would help readers understand the tradeoff.

  4. inappropriateTypes logic skips as='unknown'.
    If a prefetch link omits the as attribute, as defaults to 'unknown' (line ~99) and falls through the inappropriateTypes check silently. It is worth flagging missing-as as a warning on its own, since it prevents the browser from applying correct MIME type matching and may cause the resource to be fetched twice.

  5. Premature return inside a console.group.
    The early-exit path when no prefetch links are found (line ~77) does not call console.groupEnd() — but in this particular path no group has been opened yet, so it is fine. Worth a brief comment to make the intent clear for future editors.

  6. Minor: shortUrl can be empty.
    If href is just a bare origin (e.g., https://example.com) the split('/').pop() chain returns an empty string, then || href kicks in. The fallback works correctly, but a comment would make the intention clear.

  7. Mermaid diagram node labels with special characters.
    The stateDiagram-v2 diagram uses spaces and angle-bracket characters inside state labels (e.g., [*] transitions). Most Mermaid renderers handle this, but Nextra's bundled Mermaid version may differ. Worth testing in dev before merging.


Validate-Preload-Async-Defer-Scripts (updated file)

Strengths

  • The new "Real-World Case: Third-Party Consent Scripts" section is genuinely useful — this exact confusion comes up regularly and the comparison table is clear.
  • Switching escaped quotes (\"...\") to single-quoted template literals ('...') in console.log calls is a small but welcome readability improvement.
  • Table alignment fixes are cosmetic but keep the Markdown source tidy.

Issues / Suggestions

  1. Placeholder link for the blog post.
    Line ~1100 contains:

    **For a complete implementation guide, see:** [Optimizing Consent Scripts for Core Web Vitals](#) _(coming soon on joanleon.dev)_
    

    A bare # anchor is a broken link in the rendered docs. If the post doesn't exist yet, consider removing the hyperlink and just saying "coming soon on joanleon.dev" as plain text, then updating it with the real URL once the post is published.

  2. fetchpriority="high" claim needs a small qualification.
    The section correctly says that fetchpriority="high" on an async script causes the same priority escalation as a preload. However, the spec and Chrome's implementation mean the escalation depends on when the parser discovers the element. A brief note that this applies to scripts discovered during initial HTML parsing (not dynamically inserted scripts) would make the explanation more precise.

  3. Decision tree for consent scripts has an asymmetric branch.
    In the Mermaid graph ("Decision Tree for Consent Scripts"), the "No, late in body" branch asks "Need early download?". If the answer is "No", the recommendation is <script async> — but a script late in <body> loaded async without a preload will only be discovered when the parser reaches it. This branch might benefit from a note that late-body async is generally fine for non-critical consent scripts precisely because they do not need early download.


Navigation (_meta.json)

The new entry looks correct and consistent with the existing format.


Summary

Area Status
Code quality Good — clear structure, consistent style
Correctness Minor edge cases (cache detection, missing as attribute) worth addressing
Documentation Excellent — diagrams and examples add real value
Broken links One placeholder # anchor should be fixed before merge
Tests N/A (project has no test suite per CLAUDE.md)

The broken placeholder link (#1 in the second section) is the only change I'd consider blocking. The rest are suggestions for improvement.

Prefetch-Resource-Validation fixes:
- Add 'Duration' column to all output tables to show download times
- Improve cache detection: check encodedBodySize > 0 && transferSize === 0
  to avoid false positives for cross-origin resources without Timing-Allow-Origin
- Add warning for missing 'as' attribute (prevents MIME type matching)
- Add comment explaining 5-second heuristic for current-page detection
- Add comment clarifying early return is safe (no console.group opened yet)
- Add comment explaining shortUrl fallback for bare origin URLs
- Update documentation to include new 'missing-as' issue category
- Update Resource Analysis table to document Duration column

Validate-Preload-Async-Defer-Scripts fixes:
- Replace broken placeholder link (#) with plain text for upcoming blog post
- Add note that fetchpriority="high" behavior applies to parser-discovered scripts
- Add note explaining late-body async script decision tree branch

These changes address all feedback from code review:
#56 (comment)
@claude

claude Bot commented Feb 12, 2026

Copy link
Copy Markdown

PR Review: Add Mermaid diagrams and real-world examples

Overall this is a high-quality, well-structured addition to the documentation. The content is technically accurate and the educational value is strong. Here are my observations:


New File: Prefetch-Resource-Validation.mdx

Strengths:

  • The snippet is well-structured with an IIFE wrapper and a clean early-return pattern when no prefetch hints exist
  • Good use of named thresholds (THRESHOLDS object) instead of magic numbers, with inline comments explaining the values
  • The cacheStatus detection logic includes a useful comment about the cross-origin edge case (transferSize === 0 ambiguity)
  • The 5-second heuristic for detecting current-page resources is clearly documented as a limitation
  • console.group/console.groupEnd usage is properly balanced throughout the output

Potential Issues:

  1. console.group left open on early return (line 70–79): The early-return path logs and returns before console.group is ever opened — this is fine. But if the logic changes later (e.g., adding a group before the early return), the group would be left unclosed. Consider a note or defensive finally-style pattern for future maintainers.

  2. shortUrl truncation may collide (line 102): Using only the filename (href.split('/').pop()) to identify resources in console output means two different resources with the same filename (e.g., bundle.js from different paths) will appear identical in the table. This is a display-only issue but could confuse debugging. Consider showing the last two path segments.

  3. URL matching performance (lines 105–113, 154–162): The performanceEntries.find() loop and the inner performanceEntries.some() loop both create new URL objects on every comparison. For pages with many resource entries (50–100+), this creates significant object allocation. A pre-built URL map would be more efficient:

    const entryMap = new Map(
      performanceEntries.map(e => [new URL(e.name, location.origin).href, e])
    );
  4. isCurrentPage check excludes initiatorType !== 'link' (line 158): This correctly excludes the prefetch entry itself, but also excludes legitimate preloads (initiatorType === 'link') of the same resource that might confirm it's actually a current-page resource. Worth verifying this logic covers the intended cases.

  5. as attribute check for images (line 185): The image check depends on analysis.size being populated, which only happens when perfEntry exists. If the image hasn't loaded yet (no perfEntry), it won't be flagged — but the threshold comment (// >200KB images questionable) might imply it should. This asymmetry is worth a comment.

Minor:

  • The _meta.json entry for the new page is correctly added at the end of the loading section.
  • Mermaid diagrams are clear and add real value to the documentation. The state diagram for the prefetch lifecycle is particularly helpful.

Updated File: Validate-Preload-Async-Defer-Scripts.mdx

Changes:

  • Table formatting whitespace alignment (cosmetic, no behavior change)
  • Quote style normalization in template strings ('") — correct style for embedded attribute values in strings
  • New "Real-World Case: Third-Party Consent Scripts" section
  • New "Advanced Strategy: Server-Side Conditional Loading" section

Strengths:

  • The consent script section directly addresses a real-world misuse pattern that developers commonly reach for
  • Correctly identifies that fetchpriority="high" on an async script causes the same priority escalation problem as preload without mitigation — this is accurate and often misunderstood
  • The priority comparison table is concise and actionable
  • The note distinguishing dynamically-inserted scripts from HTML-parsed scripts is an important nuance

Potential Issues:

  1. Solution 1 example is slightly misleading (line 1013): The code shows:

    <link rel="preload" href="..." as="script" />
    <script async src="..." fetchpriority="low"></script>

    The fetchpriority="low" is on the <script> tag, but the preload link itself has no fetchpriority attribute. The preload will still initiate a Medium/High priority fetch. It's the execution priority on the script tag that's low, but the network download initiated by preload is still elevated. This is a subtle but important distinction — the preload link should also have fetchpriority="low" for the full effect:

    <link rel="preload" href="..." as="script" fetchpriority="low" />
    <script async src="..." fetchpriority="low"></script>

    This matches the existing table in the document (row 3) which already correctly shows both, but the Solution 1 example omits it from the <link> tag.

  2. "Coming soon" blog post reference (line 1126): The mention of a future blog post on joanleon.dev is helpful context but adds content that may become stale. Consider linking once the post is published, or phrasing it as "see joanleon.dev for a complete implementation guide" to avoid a dangling forward reference.


Documentation Quality

  • Mermaid diagrams render well for the supported use cases (flowcharts, sequence diagrams, state diagrams)
  • The framework-specific guidance section (Next.js, Remix, SvelteKit) is a valuable addition
  • The browser support table and cache requirements section are accurate and practical
  • All Further Reading links point to authoritative sources (MDN, web.dev, W3C, Chrome Developers, DebugBear)

Summary

The core snippet logic is sound and the documentation is thorough. The main actionable items are:

  1. Fix the fetchpriority="low" omission on the <link rel=preload> tag in Solution 1 — this is a correctness issue in the example code
  2. Consider the URL matching performance improvement for large pages
  3. Revisit the blog post forward reference before merging to main

The Mermaid diagrams add clear visual value and the real-world consent script case study addresses a genuinely common anti-pattern. Great addition to the collection.

Validate-Preload-Async-Defer-Scripts:
- Add missing fetchpriority="low" to <link rel=preload> tag in Solution 1
  This was a correctness bug - preload without fetchpriority="low" still
  escalates network priority even if script tag has fetchpriority="low"

Prefetch-Resource-Validation (comprehensive improvements):

Performance optimizations:
- Pre-normalize all URLs once into a Map (eliminates O(N×M) URL parsing)
- Use pre-built URL map for all matching operations
- Remove redundant URL parsing in nested loops
- Performance improvement: ~6000 URL objects → ~200 for typical cases

New validations:
- Detect invalid 'as' attribute values (typos like as="scriptt")
- Detect duplicate prefetch hints (same URL prefetched multiple times)
- Warn about large scripts (>1MB threshold, was missing)
- Validate 'as' attribute against list of valid values

Improved logic:
- Better cache detection: distinguish "cached" vs "unknown (CORS)"
  Handles case where CORS blocks timing info (both sizes === 0)
- Fixed inappropriateTypes to check scripts and provide detailed reasons
- Optimized isCurrentPageResource check to use pre-built map
- Added seenUrls Set to track duplicates

Code quality:
- Added validAsValues Set with all valid 'as' attribute values
- Added THRESHOLDS.largeScriptSize (1MB) for script-specific checks
- Better error messages with specific size/reason for inappropriateness
- Comments explaining CORS edge cases and validation logic

Documentation updates:
- Added "Invalid as", "Duplicate prefetch" to issue categories table
- Updated "Inappropriate type" description to mention scripts
- Cache status can now show "unknown (CORS)" in output

Addresses issues from comprehensive code review:
- URL matching performance (#8, #9 from analysis)
- Invalid 'as' validation (#7)
- Duplicate detection (#14)
- Large script detection (#4)
- Cache detection for CORS (#3)
- Current page detection optimization (#6)
@claude

claude Bot commented Feb 12, 2026

Copy link
Copy Markdown

PR Review: Add Mermaid diagrams and real-world examples

Overall this is a solid educational contribution. The new Prefetch-Resource-Validation snippet is well-structured and the additions to Validate-Preload-Async-Defer-Scripts add genuine value. Here are my observations:


New File: Prefetch-Resource-Validation.mdx

Strengths:

  • The snippet code is well-written — IIFE wrapping, early return for the no-prefetch case, pre-built URL map for performance, duplicate tracking with a Set, and clear issue categorization.
  • console.group/console.table usage is consistent with the existing codebase style.
  • Thorough documentation: tables, Mermaid diagrams, real-world examples, and framework-specific guidance all add significant value.
  • The CORS caveat in the cache status detection comment is a nice detail.

Potential issues / suggestions:

  1. shortUrl edge case — the filename extraction relies on splitting on / and ?:

    const shortUrl = href.split("/").pop()?.split("?")[0] || href;

    For URLs like https://cdn.example.com/ or https://cdn.example.com/?foo=bar, pop() returns "" or "?foo=bar", so || href correctly falls back. But for hash-only URLs (e.g. https://example.com/page#section) the hash will remain in shortUrl. Minor cosmetic issue worth noting.

  2. as === "media" is not a valid value — the validAsValues Set does not include "media", yet the inappropriateness check has a special branch for as === "video" || as === "media". If as="media" is encountered, it would first be flagged as invalid-as and then reach the isInappropriate branch. This is logically harmless but slightly inconsistent. Consider removing || as === "media" since it is not a spec-compliant value.

  3. 5-second heuristic — the existing code comment acknowledges this can produce false positives on slow/large pages, which is great. Consider surfacing this caveat in the documentation too (not just in code comments) so users running the snippet understand why they might see false wrong-hint errors.

  4. countIssues vs per-resource issues — the "Issues found" summary mixes per-resource issues with aggregate issues. A resource with a not-loaded info warning contributes to issues.length, which can make the summary count misleading (e.g., "5 issues found" where 3 are just "not loaded yet"). Not a bug, but worth considering for clarity.

  5. fetch() example in "Verify cache headers" section — this makes a real network request and sits outside the main copy-fenced block. A short note clarifying it is a standalone illustrative example (not part of the diagnostic snippet) would help avoid confusion.


Changes to Validate-Preload-Async-Defer-Scripts.mdx

Strengths:

  • The new "Real-World Case: Third-Party Consent Scripts" section is genuinely useful and addresses a very common misunderstanding.
  • Correctly explains that fetchpriority="high" on async is as harmful as preload — a nuance many developers miss.
  • The priority comparison table is clear and actionable.
  • Quote-style fixes (\" to single-quoted strings) are clean improvements.

Minor points:

  1. "A detailed blog post is coming soon on joanleon.dev" — forward references to unpublished content can become stale. Consider replacing with a real link once published, or removing this forward reference until then.

  2. Dynamic script injection caveat — the note about dynamically injected scripts behaving differently is slightly buried. Since consent scripts are frequently loaded via tag managers (dynamic insertion), a brief mention in the comparison table or decision tree would make this more visible.


Navigation / Meta

  • _meta.json correctly adds the new page entry. The ordering (after Validate-Preload-Async-Defer-Scripts) is logical.

Summary

Area Assessment
Code correctness ✅ Solid — no bugs found, minor edge cases noted
Documentation quality ✅ High — diagrams and tables improve comprehension
Mermaid diagrams ✅ Clear and accurate
Style / conventions ✅ Follows existing project patterns
Minor issues See notes above — none are blocking

This PR is ready to merge. The items above are optional improvements rather than blockers.

Prefetch-Resource-Validation fixes:

1. Fix shortUrl hash handling:
   - Now removes both query params and hash fragments
   - Prevents URLs like "page#section" from showing hash in console output
   - Comment documents this behavior

2. Remove "media" from inappropriateness check:
   - Changed from `as === "video" || as === "media"` to `as === "video" || as === "audio"`
   - "media" is not a valid HTML spec value for 'as' attribute
   - Added comment in validAsValues explaining this
   - More consistent: invalid "as" values get flagged by validator first

3. Document 5-second heuristic limitation:
   - Added note in Issue Categories table explaining false positives on slow pages
   - Makes users aware of limitation when evaluating "wrong hint type" errors
   - Complements existing code comment

4. Improve issue count clarity:
   - Separate "meaningful issues" (errors/warnings) from info-level (not loaded)
   - Summary now says: "Issues found: X (excluding 'not loaded' info)"
   - Prevents misleading count where most "issues" are just "pending" resources
   - Uses totalMeaningfulIssues in both summary and final message

5. Clarify fetch() example is standalone:
   - Added note before cache header verification example
   - Makes clear it's NOT part of the diagnostic snippet
   - Warns it makes a real network request
   - Prevents confusion about running standalone code

These changes address all suggestions from latest review round:
- shortUrl edge case with hashes
- as="media" spec inconsistency
- 5s heuristic documentation
- Issue count clarity
- fetch() example clarification
CVE-2026-0969: Vulnerable version of next-mdx-remote (4.4.1) detected.

Solution:
- Added npm overrides to force next-mdx-remote@^6.0.0
- This overrides the transitive dependency from nextra@2.13.4
- Build tested and working correctly

The override ensures Vercel deployment won't be blocked by the security check.

Learn more: https://vercel.link/CVE-2026-0969
@claude

claude Bot commented Feb 12, 2026

Copy link
Copy Markdown

PR Review: Add Mermaid Diagrams and Real-World Examples

Summary

This PR adds two main things:

  1. A new Prefetch-Resource-Validation.mdx snippet with comprehensive documentation and Mermaid diagrams
  2. Extended Validate-Preload-Async-Defer-Scripts.mdx with real-world consent script guidance

The content is well-researched and genuinely useful. Below are observations across both content quality and technical concerns.


Strengths

  • New snippet (Prefetch-Resource-Validation.mdx) is high quality: the JavaScript is well-structured, uses IIFE pattern consistent with the repo, properly handles edge cases (CORS timing, early-return before console.group, URL normalization), and includes thorough inline comments explaining non-obvious decisions (e.g. the 5-second heuristic for isCurrentPage, CORS transferSize ambiguity).
  • Real-world consent script section is a great addition — it addresses a genuinely common misconception about preload + async and explains why fetchpriority="high" does not solve the problem.
  • Tables and decision trees improve comprehension; the priority comparison table for consent script scenarios is especially clear.
  • Thresholds are documented — the rationale for 500KB, 2MB, 5MB limits is explained inline.
  • The shortUrl extraction correctly uses optional chaining with a || href fallback for edge cases.

Issues to Address

1. Mermaid diagrams — not supported by Nextra without a plugin

The MDX files contain 7 Mermaid diagrams (triple-backtick mermaid code blocks). Nextra's default nextra-theme-docs does not render Mermaid diagrams — they will appear as raw code blocks in the browser.

The package.json diff shows 3 additions but the full content was not visible in the diff. If rehype-mermaid or a similar plugin was added, please verify it is configured in next.config.js as a rehypePlugin. If not, either:

  • Add and configure a Mermaid plugin (e.g. rehype-mermaid, or @theguild/remark-mermaid), or
  • Replace diagrams with static ASCII/table equivalents, or
  • Replace with static SVG/PNG images hosted via Cloudinary (consistent with how the homepage uses CldVideoPlayer)

This is a blocking concern — the diagrams are central to the new content's value.

2. package.json changes not shown in diff

The diff shows +3 -0 in package.json but the content was not included in the diff preview. Please confirm what packages were added and that they are actually used. The package-lock.json is 7K+ lines of additions, suggesting significant new dependencies were introduced.


Warnings

3. package-lock.json noise

The package-lock.json diff is ~11K lines, largely consisting of adding "dev": true and "peer": true markers to existing entries plus removing @types/js-yaml. This looks like a lock file regenerated with a different npm version. While not wrong, it creates noisy diffs and could mask real dependency changes. Consider regenerating from a clean state or separating this into its own commit.

4. Hardcoded 5-second heuristic — documented but worth surfacing at runtime

The snippet's "current page resource" detection:

const isCurrentPageResource = matchingEntries.some(
  (entry) => entry.initiatorType !== "link" && entry.startTime < 5000,
);

The inline comment and documentation both acknowledge the false-positive risk on slow pages. Consider also logging a console warning when the page's own performance.timing.loadEventEnd exceeds 5000ms, to alert users running the snippet on slow pages that results may be inaccurate.

5. shortUrl comment is inaccurate

const shortUrl = href.split("/").pop()?.split("?")[0]?.split("#")[0] || href;

The comment says "Removes query params but preserves hash" — but it actually strips the hash too (.split("#")[0]). Also, for URLs with a trailing slash (e.g. https://example.com/path/), .pop() returns "", which triggers the || href fallback. The comment should be updated to accurately describe this behavior.

6. Forward-reference to unpublished blog post

A detailed blog post is coming soon on joanleon.dev

Avoid referencing unpublished content in documentation. Either link to the live post or remove this sentence until it is published.


Minor Suggestions

  • validAsValues includes "video" and "audio" as spec-valid values, but the snippet then flags as="video" or as="audio" as "typically too large for prefetch." This is intentional (spec-valid != practically appropriate), but a short comment clarifying the distinction would prevent confusion.

  • cacheStatus property is only set on analysis when a perfEntry exists, but is referenced as item.cacheStatus || "N/A". The || "N/A" fallback handles it, but initializing cacheStatus: null in the analysis object literal would make the shape more predictable.

  • Navigation ordering in _meta.json: Prefetch-Resource-Validation is appended last. Consider placing it adjacent to Validate-Preload-Async-Defer-Scripts since both deal with resource hints — they are conceptually related.

  • The statement "fetchpriority='high' on an async script has the same negative effect as preloading it" is approximately correct for scripts parsed from HTML, but the nuance about dynamically injected scripts (noted in the inline callout) deserves slightly more prominence, as it is a common source of confusion.

@nucliweb nucliweb merged commit f882439 into main Feb 12, 2026
3 checks passed
@nucliweb nucliweb deleted the snippet/Prefetch-Resource-Validation branch February 12, 2026 16:13
nucliweb added a commit that referenced this pull request Feb 25, 2026
Prefetch-Resource-Validation fixes:
- Add 'Duration' column to all output tables to show download times
- Improve cache detection: check encodedBodySize > 0 && transferSize === 0
  to avoid false positives for cross-origin resources without Timing-Allow-Origin
- Add warning for missing 'as' attribute (prevents MIME type matching)
- Add comment explaining 5-second heuristic for current-page detection
- Add comment clarifying early return is safe (no console.group opened yet)
- Add comment explaining shortUrl fallback for bare origin URLs
- Update documentation to include new 'missing-as' issue category
- Update Resource Analysis table to document Duration column

Validate-Preload-Async-Defer-Scripts fixes:
- Replace broken placeholder link (#) with plain text for upcoming blog post
- Add note that fetchpriority="high" behavior applies to parser-discovered scripts
- Add note explaining late-body async script decision tree branch

These changes address all feedback from code review:
#56 (comment)
nucliweb added a commit that referenced this pull request Feb 25, 2026
…tion

Add Mermaid diagrams and real-world examples for script loading validation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant