{"data":{"slug":"discovered-e06e5c9c407657d6e775b757fb47454f4c113dee98bf849f","title":"Browser Performance Audit","summary":"Perform a browser tab performance audit by collecting Navigation Timing, Core Web Vitals, resource loading, console errors, and DOM structure, then cross-validate and output prioritized optimization suggestions. Use when the user asks to evaluate page performance, diagnose slow loading, analyze memory leaks, or investigate long-session degradation.","url":"https:\/\/skillshunter.net\/skills\/discovered-e06e5c9c407657d6e775b757fb47454f4c113dee98bf849f","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-e06e5c9c407657d6e775b757fb47454f4c113dee98bf849f","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-e06e5c9c407657d6e775b757fb47454f4c113dee98bf849f.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-e06e5c9c407657d6e775b757fb47454f4c113dee98bf849f\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before using the `javascript_tool`, ensure that multi-statement probes are written as IIFE (Immediately Invoked Function Expressions) and avoid using `return` at the top level. Additionally, always perform a clean navigation by creating a fresh tab and navigating it yourself for first-load audits, rather than using an existing tab.","instructions":"---\nname: browser-performance-audit\ndescription: \"Perform a browser tab performance audit: collect Navigation Timing, Core Web Vitals, resource loading, console errors, and DOM structure, then cross-validate and output prioritized optimization suggestions. Use when the user asks to evaluate page performance, diagnose slow loading, analyze memory leaks, or investigate long-session degradation.\"\nmetadata:\n  author: \u6768\u4fca\u5b81\n  email: luozhu2021@gmail.com\n---\n\n# Browser Performance Audit\n\n## When to Use\n\n- User asks to \"evaluate\/audit\/test page performance\"\n- User reports a page is slow, laggy, or consuming too much memory\n- User wants to understand what's blocking first paint or interactivity\n- User suspects long-session degradation (memory leak, DOM bloat)\n- Keywords: \u6027\u80fd\u8bc4\u6d4b, \u9875\u9762\u6027\u80fd, \u52a0\u8f7d\u6162, Core Web Vitals, FCP, LCP, \u5185\u5b58\u6cc4\u6f0f, \u957f\u65f6\u52a3\u5316\n\n## Prerequisites\n\n- `builtin_browser` MCP tools must be available (javascript_tool, read_console_messages, read_page, read_network_requests, tabs_create, navigate)\n- Call `qw_mcp_get` on each browser tool before first use in a session. Signatures differ: `tabs_create` takes **no arguments at all** and returns a new tabId, while `navigate`, `javascript_tool` and `read_network_requests` all require an explicit `tabId`.\n- Never audit a tab that was already open. See the iron laws below \u2014 this is not a soft preference.\n\n## Iron laws\n\nThese exist because ignoring them has already produced a fully fabricated\ndiagnosis. A real case: an audit reported FCP 4824ms, 130 first-screen scripts\nand 6.7MB HTML, and derived two optimization proposals from those numbers. All of\nit was wrong \u2014 sampling happened on a tab open ~19 minutes. After one clean\nnavigation the true values were FCP 908ms and 13 scripts, and both proposals were\nvoid. The \"2.8s gap between first-paint and FCP\" that drove the whole analysis\nwas an artifact of the resource-timing 250-entry cap.\n\n**1. Clean navigation is mandatory, not advisory.** For any first-load question,\ncreate a fresh tab and navigate it yourself in the current turn. If page age is\nlarge, the correct action is to re-navigate \u2014 **not** to ask the user whether to\nproceed with an accumulated-state audit. There is no valid \"continue anyway\" path\nfor first-load metrics.\n\n**2. `javascript_tool` forbids top-level `return`.** Its contract states the\nresult of the last expression is returned automatically and `return` must not be\nused. Every multi-statement probe must be an IIFE. Getting `undefined` on a first\nprobe attempt almost always means it was written as bare statements \u2014 rewrite as\nIIFE rather than concluding the API is unavailable.\n\n**3. Count resources from `read_network_requests`, not resource timing.** The\npage buffer caps at 250 entries and silently evicts the oldest. `read_network_requests`\nis not bound by it. Use resource timing only for per-resource cache\/protocol\nprobing, always alongside its truncation flag.\n\n**4. Never present an accumulated metric as a first-screen figure.** DOM nodes,\n`outerHTML` size, element counts and JS heap describe *right now*. Label each one\nwith its sample age.\n\n**5. No proposal without a verified bottleneck.** See \"Falsify before proposing\".\n\n## Steps\n\n### 0. Clean navigation (required for first-load audits)\n\n```\ntabs_create                                    \u2192 returns tabId (no arguments)\nread_network_requests { tabId, clear: true }    \u2192 drop stale records\nnavigate { tabId, url }\n```\n\nImmediately after navigation completes, raise the buffer for the new document:\n\n```javascript\n(() => { performance.setResourceTimingBufferSize(3000); return 'ok'; })()\n```\n\nNote this helps but does not guarantee completeness \u2014 the buffer cannot be\npre-set before the document exists, since the performance timeline is rebuilt per\ndocument. Treat resource timing as best-effort regardless.\n\nIf the target requires authentication, a fresh tab inherits the user's session,\nwhich is the reason to use `builtin_browser` rather than an isolated automation\nprofile. If the page redirects to a login form, stop and report it \u2014 do not\nmeasure the login page.\n\nSkip this step only when the user explicitly asks about accumulated runtime state\n(long-session degradation), in which case label the entire report accordingly.\n\n### 1. Environment Confirmation\n\nIdentify the target tab and check page age:\n\n```javascript\n\/\/ Inject via javascript_tool\n(() => {\n  const nav = performance.getEntriesByType('navigation')[0] || {};\n  const now = performance.now();\n  const pageAgeMs = now;\n  const ua = navigator.userAgent;\n  return JSON.stringify({\n    url: location.href,\n    pageAgeSeconds: Math.round(pageAgeMs \/ 1000),\n    navigationType: nav.type, \/\/ \"navigate\", \"reload\", \"back_forward\"\n    ua,\n    warning: pageAgeMs > 300000 ? \"Page has been open > 5 min. Resource Timing buffer may have overflowed; DOM and heap reflect accumulated state, not first-load. Recommend reload for accurate first-load audit.\" : null\n  });\n})()\n```\n\nIf `warning` is non-null and the user asked a first-load question, go back to\nstep 0 and re-navigate. Do **not** offer to proceed with the aged sample \u2014 that\nis exactly how the fabricated-diagnosis case happened. Only proceed on an aged\ndocument when the user explicitly asked about accumulated runtime state, and then\nlabel every number in the report with its sample age.\n\n### 2. Navigation & Rendering Timing\n\n```javascript\n(() => {\n  const nav = performance.getEntriesByType('navigation')[0] || {};\n  const paint = {};\n  performance.getEntriesByType('paint').forEach(e => { paint[e.name] = Math.round(e.startTime); });\n\n  return JSON.stringify({\n    protocol: nav.nextHopProtocol,\n    redirectTime: Math.round((nav.redirectEnd || 0) - (nav.redirectStart || 0)),\n    dnsTime: Math.round((nav.domainLookupEnd || 0) - (nav.domainLookupStart || 0)),\n    tcpTime: Math.round((nav.connectEnd || 0) - (nav.connectStart || 0)),\n    tlsTime: nav.secureConnectionStart > 0 ? Math.round((nav.connectEnd || 0) - nav.secureConnectionStart) : 0,\n    ttfb: Math.round(nav.responseStart || 0),\n    responseTime: Math.round((nav.responseEnd || 0) - (nav.responseStart || 0)),\n    domInteractive: Math.round(nav.domInteractive || 0),\n    domContentLoaded: Math.round(nav.domContentLoadedEventEnd || 0),\n    loadComplete: Math.round(nav.loadEventEnd || 0),\n    firstPaint: paint['first-paint'] || null,\n    firstContentfulPaint: paint['first-contentful-paint'] || null,\n    transferSize: nav.transferSize,\n    encodedBodySize: nav.encodedBodySize,\n    decodedBodySize: nav.decodedBodySize\n  });\n})()\n```\n\n### 3. Core Web Vitals & Long Tasks\n\n```javascript\n(() => {\n  \/\/ LCP - read from existing entries\n  const lcpEntries = performance.getEntriesByType('largest-contentful-paint');\n  const lcp = lcpEntries.length > 0 ? Math.round(lcpEntries[lcpEntries.length - 1].startTime) : null;\n\n  \/\/ CLS - approximate from layout-shift entries\n  const layoutShifts = performance.getEntriesByType('layout-shift');\n  let cls = 0;\n  let sessionValue = 0;\n  let sessionEntries = [];\n  layoutShifts.forEach(entry => {\n    if (!entry.hadRecentInput) {\n      if (sessionEntries.length && entry.startTime - sessionEntries[sessionEntries.length - 1].startTime > 5000) {\n        cls = Math.max(cls, sessionValue);\n        sessionValue = 0;\n        sessionEntries = [];\n      }\n      sessionValue += entry.value;\n      sessionEntries.push(entry);\n    }\n  });\n  cls = Math.max(cls, sessionValue);\n\n  \/\/ Long Tasks\n  const longTasks = performance.getEntriesByType('longtask');\n  const totalBlockingTime = longTasks.reduce((sum, t) => sum + Math.max(0, t.duration - 50), 0);\n\n  return JSON.stringify({\n    lcp,\n    cls: Math.round(cls * 10000) \/ 10000,\n    longTaskCount: longTasks.length,\n    totalBlockingTime: Math.round(totalBlockingTime),\n    longestTask: longTasks.length > 0 ? Math.round(Math.max(...longTasks.map(t => t.duration))) : 0\n  });\n})()\n```\n\nNote: LCP and layout-shift entries require `PerformanceObserver` with `buffered: true` to have been registered. If entries are empty, it means no observer was set up. In that case, note the limitation and skip.\n\n### 4. Resource Loading Analysis\n\n**Authoritative resource inventory comes from `read_network_requests`, not from\nresource timing.** Call it first \u2014 it is not bound by the page's 250-entry buffer:\n\n```\nread_network_requests { tabId, limit: 1000 }\n```\n\nUse it to establish true counts by type, failed requests, and total volume. Only\nthen use resource timing below for per-resource cache\/protocol detail, and treat\nits aggregate counts as a lower bound whenever `bufferFull` is true.\n\n```javascript\n(() => {\n  const resources = performance.getEntriesByType('resource');\n  const bufferFull = resources.length >= 250; \/\/ Chrome default limit\n\n  const byType = {};\n  const byProtocol = {};\n  let cacheHits = 0;\n  let totalTransfer = 0;\n  let totalDecoded = 0;\n\n  resources.forEach(r => {\n    const type = r.initiatorType || 'other';\n    if (!byType[type]) byType[type] = { count: 0, transferKB: 0, avgDurationMs: 0, durations: [] };\n    byType[type].count++;\n    byType[type].transferKB += (r.transferSize || 0) \/ 1024;\n    byType[type].durations.push(r.duration);\n\n    const proto = r.nextHopProtocol || '(empty)';\n    byProtocol[proto] = (byProtocol[proto] || 0) + 1;\n\n    if (r.transferSize === 0 && r.decodedBodySize > 0) cacheHits++;\n    totalTransfer += r.transferSize || 0;\n    totalDecoded += r.decodedBodySize || 0;\n  });\n\n  \/\/ Compute averages\n  Object.values(byType).forEach(v => {\n    v.avgDurationMs = Math.round(v.durations.reduce((a, b) => a + b, 0) \/ v.durations.length);\n    v.transferKB = Math.round(v.transferKB);\n    delete v.durations;\n  });\n\n  return JSON.stringify({\n    totalResources: resources.length,\n    bufferFull,\n    bufferWarning: bufferFull ? \"Resource Timing buffer is full (250). Early entries may have been evicted. Numbers below are INCOMPLETE.\" : null,\n    cacheHitRate: resources.length > 0 ? Math.round(cacheHits \/ resources.length * 100) + '%' : 'N\/A',\n    totalTransferKB: Math.round(totalTransfer \/ 1024),\n    totalDecodedKB: Math.round(totalDecoded \/ 1024),\n    byInitiatorType: byType,\n    byProtocol\n  });\n})()\n```\n\n### 5. DOM Structure & Memory\n\n```javascript\n(() => {\n  const allElements = document.querySelectorAll('*').length;\n  const scripts = document.querySelectorAll('script[src]').length;\n  const inlineScripts = document.querySelectorAll('script:not([src])').length;\n  const stylesheets = document.querySelectorAll('link[rel=\"stylesheet\"]').length;\n  const iframes = document.querySelectorAll('iframe').length;\n  const images = document.querySelectorAll('img').length;\n  const maxDepth = (() => {\n    let max = 0;\n    const walk = (el, depth) => {\n      if (depth > max) max = depth;\n      if (depth > 32) return; \/\/ safety cap\n      for (const child of el.children) walk(child, depth + 1);\n    };\n    walk(document.documentElement, 0);\n    return max;\n  })();\n\n  \/\/ Memory (Chromium only)\n  const memory = performance.memory ? {\n    usedJSHeapMB: Math.round(performance.memory.usedJSHeapSize \/ 1048576),\n    totalJSHeapMB: Math.round(performance.memory.totalJSHeapSize \/ 1048576),\n    heapLimitMB: Math.round(performance.memory.jsHeapSizeLimit \/ 1048576)\n  } : null;\n\n  return JSON.stringify({\n    totalDOMNodes: allElements,\n    externalScripts: scripts,\n    inlineScripts,\n    stylesheets,\n    iframes,\n    images,\n    maxDOMDepth: maxDepth,\n    memory\n  });\n})()\n```\n\n### 6. Console Errors\n\nCall `read_console_messages` on the target tab. Categorize messages by level (error, warning). Focus on:\n\n- Uncaught exceptions and unhandled promise rejections\n- Failed network requests (4xx\/5xx, CORS errors)\n- Deprecation warnings that may affect future compatibility\n\n### 7. Cross-Validation\n\nAfter collecting all data, perform these sanity checks:\n\n1. **Buffer overflow detection**: If `bufferFull` is true AND navigation timing shows page age > 60s, warn that resource data is incomplete and first-load analysis cannot be done from current state.\n2. **Timing consistency**: Compare `firstContentfulPaint` with the earliest resource `startTime`. If the earliest resource startTime is orders of magnitude larger than FCP (e.g., > 100x), the buffer has rotated and early resources are lost \u2014 do NOT use resource timing for waterfall analysis.\n3. **Accumulated state detection**: If DOM nodes > 5000 but external scripts < 20, the page likely uses keep-alive\/SPA routing that accumulates DOM without new script loads. Flag this as \"accumulated state\" and note that DOM count reflects runtime, not first-load.\n4. **Memory baseline**: If `usedJSHeapMB` > 200MB on a page open < 5 minutes, flag as potential memory issue. If page has been open > 30 minutes and heap is > 100MB, note that delta from initial load would be needed to judge leak.\n\n### 7.5 Falsify before proposing\n\nFor every candidate optimization, write down three things and **drop the proposal\nif any of them fails**:\n\nThe measured evidence that the bottleneck exists, quoted with metric name and\nvalue. The counter-test that would disprove it, and its result. Whether that\nevidence is a true first-screen metric or an accumulated one \u2014 if accumulated, the\nproposal is void until re-measured on a clean navigation.\n\nWorked example of a correctly killed proposal. Candidate: enlarge disk\/code cache\nto speed up boot scripts. Evidence sought: boot resources with non-zero\n`transferSize` and meaningful `duration`. Actual probe result: `transferSize: 0`,\n`decodedBodySize: 11440`, `proto: h2`, `duration: 2.6ms` \u2014 already a cache hit.\nThe problem does not exist; the proposal was dropped before being presented.\n\nTwo recurring premise failures worth checking explicitly. A caching proposal is\nvoid if the targeted resources already show `transferSize === 0` \u2014 and note that\ncaching changes carry cross-session staleness risk, raising the bar further. A\nconnection-level proposal (preconnect, domain sharding, reducing request count)\nis largely void if `nextHopProtocol` is already `h2`\/`h3`, since multiplexing has\ncaptured most of that gain.\n\nWhen an earlier number turns out wrong, lead the report with the correction and\nshow a before\/after table. A plainly stated retraction is far cheaper than a wrong\nrecommendation that reaches implementation.\n\n### 8. Report Template\n\nStructure the final output as:\n\n```\n## Performance Audit Summary\n\n**Target**: [URL]\n**Measured at**: [page age] after navigation\n**Type**: [first-load | accumulated-state]\n\n### Key Metrics\n| Metric | Value | Rating |\n|--------|-------|--------|\n| TTFB | Xms | Good\/Needs Work\/Poor |\n| FCP | Xms | ... |\n| LCP | Xms | ... |\n| CLS | X | ... |\n| TBT | Xms | ... |\n| DOM Nodes | X | ... |\n| JS Heap | XMB | ... |\n\nRating thresholds (per web.dev):\n- FCP: Good < 1800ms, Poor > 3000ms\n- LCP: Good < 2500ms, Poor > 4000ms\n- CLS: Good < 0.1, Poor > 0.25\n- TBT: Good < 200ms, Poor > 600ms\n- TTFB: Good < 800ms, Poor > 1800ms\n\n### Critical Issues\n[Items that severely impact UX \u2014 must fix]\n\n### Important Improvements\n[Items with measurable benefit \u2014 should fix]\n\n### Suggestions\n[Nice-to-have optimizations \u2014 consider fixing]\n\n### Data Validity Notes\n[Any cross-validation warnings about measurement accuracy]\n```\n\nFor each issue, include: what it is, estimated impact, who owns the fix (browser-layer vs site-layer), and risk assessment.\n\n## Pitfalls\n\n- **`javascript_tool` rejects top-level `return`**: The tool returns the value of the last expression and its contract explicitly forbids `return`. Any multi-statement probe must be wrapped as `(() => { ... })()`. An `undefined` result on a first attempt is almost always this mistake, not a missing API.\n- **Recognizing buffer truncation in the wild**: The signal is an entry count pinned at exactly 250 plus `startTime` values orders of magnitude larger than any paint timestamp (e.g. 10^6 ms). The downstream symptom is a \"mysterious gap\" between paint and resource completion that no code path explains \u2014 that gap is the artifact, not a real bottleneck.\n- **Recognizing keep-alive accumulation**: DOM nodes, heap and element counts all grow with page age while paint timing stays constant across clean reloads. Confirm by comparing two clean navigations against one aged sample: if the two clean runs agree and the aged one is the outlier, the aged numbers are accumulation, not regression.\n- **Large HTML size is not proof of server-side data injection**: On keep-alive architectures, switching views often only sets `content-visibility: hidden` and leaves the old subtree in the document, so `outerHTML` size is cumulative by design. Verify what the server actually returned before blaming the response.\n- **Long-session degradation needs two phases, not one sample**: Separate one-time mount cost from a genuine leak by sampling after each incremental view activation, then holding the page idle and continuing to sample. A curve that plateaus once all views are active means bounded mount cost; continued growth while idle means a real leak. With only one phase measured, both hypotheses stay open and neither should be asserted.\n- **`Glob` silently returns nothing for ignore-excluded paths**: Zero matches looks identical to \"directory does not exist\". When a directory is known or likely to exist but `Glob` finds nothing, re-check with Bash `ls`\/`find` before concluding it is absent.\n- **Resource Timing Buffer 250-entry limit**: Chrome's default buffer holds 250 resource entries. On heavy SPA pages, early entries get evicted after a few minutes. Always check `bufferFull` before drawing conclusions from resource data. A page that loaded 130 scripts at boot may show only 30 if measured late.\n- **Accumulated-state measurement bias**: On keep-alive SPA pages (e.g., using `content-visibility: hidden`), DOM only grows. Measuring DOM nodes or `outerHTML` size after the page has been open reflects accumulated state, NOT first-load cost. Always note page age.\n- **`performance.memory` is Chromium-only**: Firefox and Safari don't expose it. The API is also deprecated in favor of `measureUserAgentSpecificMemory()` (requires cross-origin isolation). Check availability before using.\n- **`transferSize: 0` ambiguity**: This can mean either disk cache hit (when `decodedBodySize > 0`) OR CORS opaque response (when `decodedBodySize === 0`). Always check `decodedBodySize` to distinguish.\n- **LCP\/CLS entries may be empty**: These require `PerformanceObserver` with `buffered: true` to have been set up by the page or injected early. If the page doesn't register one, and we inject after load, entries may be unavailable. Note this limitation rather than reporting \"LCP = 0\".\n- **SPA navigation breaks Navigation Timing**: If the page does client-side routing, `performance.getEntriesByType('navigation')` still reflects the initial hard navigation, not subsequent route changes. Clarify which navigation is being measured.\n\n## Verification\n\nEvery item below must be a yes before writing any conclusion.\n\n- Navigation was performed in this session (step 0) and reported page age is small\n- Paint and navigation timing pass the order-of-magnitude sanity check against each other\n- Every DOM\/heap number is explicitly labeled as accumulated state, with its sample age\n- Resource counts come from `read_network_requests`; any resource-timing figure is presented together with its `bufferFull` flag\n- Each proposal names its supporting metric and its counter-test result (step 7.5)\n- Any earlier conclusion contradicted by clean data is explicitly retracted, not quietly dropped\n- Confirm all injected scripts are pure reads with no side effects (no DOM mutation, no network requests, no `localStorage` writes)\n- After Step 7 cross-validation, if any warning fires, prominently note it in the report rather than presenting potentially invalid data as fact\n- Compare `nav.startTime` (should be 0) with first resource entry's `startTime` \u2014 if the gap is unreasonably large (> 60s), the measurement is from an accumulated session\n- For memory leak investigation, take two measurements 5+ minutes apart and compare delta rather than relying on a single snapshot\n","use_cases":["Evaluate page performance","Diagnose slow loading","Analyze memory leaks","Investigate long-session degradation"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/youngjunning\/joyally-skills\/blob\/226e1607ad781c3f876effcda4b71088f5425e0e\/skills\/engineering\/browser-performance-audit\/SKILL.md","source_commit":"226e1607ad781c3f876effcda4b71088f5425e0e","license":null,"version":null,"listing_approved_at":"2026-11-29","created_at":"2026-11-28T18:42:58.000000Z","updated_at":"2026-11-29T10:53:14.000000Z","seo_title":"Browser Performance Audit Tool","seo_description":"Audit browser performance with detailed metrics on navigation timing, Core Web Vitals, resource loading, and DOM structure. Get prioritized optimization suggestions for a","seo_keywords":["performance audit","page performance","Core Web Vitals","FCP","LCP","memory leak","long-session degradation"]}}