Measure Page Weight with JavaScript Resource Timing

A repeat visit can hide the most expensive part of a page. A hero image that appears instantly on your laptop might cost a new mobile visitor a megabyte. The browser’s Resource Timing API can show which downloads account for the difference. Measure the same page with a cold and a warm cache before deciding what to change.

Know which bytes you are measuring

The size of a resource on disk is not necessarily the size of its HTTP response. Compression, caching and browser privacy restrictions all affect the figures available to JavaScript.

Three Resource Timing properties are especially useful:

PropertyWhat it represents
encodedBodySizeResponse body size before removing HTTP content encoding
decodedBodySizeResponse body size after removing HTTP content encoding
transferSizeBrowser-reported transfer size, accounting for network delivery and cache behavior

A JavaScript file might have a decoded body of 180,000 bytes but an encoded body of only 48,000 bytes after Brotli compression. A subsequent visit may reuse the cached response without transferring that body again.

For a freshly downloaded response, the browser adds a fixed 300 bytes to the encoded body size to account for headers. A revalidated cached response can report just 300 bytes. That figure alone cannot distinguish revalidation from an empty response fetched over the network. Check the status in the Network panel. MDN explains how the browser calculates transferSize.

Build a page-weight report in DevTools

Open a page on your own website, wait for it to finish loading and paste the following into the browser’s developer console. The function groups completed entries by the mechanism that initiated the request and shows the largest reported transfers.

function auditPageWeight(perf = performance) {
  const entries = [
    ...perf.getEntriesByType('navigation'),
    ...perf.getEntriesByType('resource')
  ];
  const groups = new Map();
  const rows = [];

  for (const entry of entries) {
    const type = entry.entryType === 'navigation'
      ? 'document'
      : entry.initiatorType || 'other';
    const url = new URL(entry.name);
    const transfer = entry.transferSize;
    const encoded = entry.encodedBodySize;
    const decoded = entry.decodedBodySize;
    const unknown = transfer === 0 && encoded === 0 && decoded === 0;
    const cacheCandidate = transfer === 0 && decoded > 0;

    const row = {
      type,
      // Do not include query parameters or fragments in the report.
      resource: ['http:', 'https:'].includes(url.protocol)
        ? url.origin + url.pathname : url.protocol,
      transfer,
      encoded,
      decoded,
      durationMs: Math.round(entry.duration),
      status: unknown ? 'zero or unavailable'
        : cacheCandidate ? 'possible cache reuse' : 'reported'
    };
    rows.push(row);

    const group = groups.get(type) || {
      type, count: 0, transfer: 0, encoded: 0,
      decoded: 0, zeroOrUnavailable: 0
    };
    group.count++;
    group.transfer += transfer;
    group.encoded += encoded;
    group.decoded += decoded;
    if (unknown) group.zeroOrUnavailable++;
    groups.set(type, group);
  }

  const total = rows.reduce((sum, row) => sum + row.transfer, 0);
  return {
    totalReportedBytes: total,
    groups: [...groups.values()].sort((a, b) => b.transfer - a.transfer),
    resources: rows.sort((a, b) => b.transfer - a.transfer)
  };
}

const report = auditPageWeight();
console.table(report.groups);
console.table(report.resources.slice(0, 15));
console.log('Reported transfer:', report.totalReportedBytes, 'bytes');

The navigation entry is included so that the initial HTML document is not overlooked. The resource entries cover subsequent requests visible in the current document’s performance timeline.

The grouping is by initiator, not MIME type. For instance, an image retrieved through CSS may be classified differently from an image loaded through an HTML img element. Fetch requests can represent anything from JSON to binary data. Use the Network panel to investigate ambiguous entries.

This is a snapshot, not a complete network accounting system. It does not automatically include resources inside other frames, all worker requests or entries that have already been discarded. A large document can fill the resource timing buffer. For an instrumented test page, call performance.setResourceTimingBufferSize(2000) early, and use a PerformanceObserver if you need to collect entries throughout a longer session.

Investigate zero-byte resources before celebrating

A zero transfer size accompanied by a positive decoded size can indicate local cache reuse when the relevant timing information is available. A resource with all three sizes set to zero is less informative. It could be empty, or the browser might be withholding its size.

Cross-origin assets are an important example. If you operate a separate asset origin, you may need to return a header such as:

Timing-Allow-Origin: https://www.example.com

This lets the specified page origin see additional timing fields. Reading cross-origin body sizes can also require a CORS-enabled request and response. A transfer of 300 bytes with hidden body sizes therefore needs a closer look.

Check the response headers of a resource you control:

curl -sS -D - -o /dev/null 'https://assets.example.com/app.js'

The cURL command line builder can help assemble a reproducible request with the correct URL and headers. cURL does not enforce browser timing or CORS restrictions, so confirm the result in a real browser as well.

Compare cold and warm visits

  1. Start in a fresh browser profile with caching enabled. Open the page, wait for the requests you want to count, then run the report and save the totals. This first visit also populates the cache.
  2. Navigate away and open the same URL again in the same profile. Use a normal navigation and avoid the Back button, which can restore the whole document. Wait for the same requests and run the report again.

Keep the browser, viewport, page content and network profile consistent. Service workers can introduce their own cache behavior, so record whether one is active. For a page with lazy-loaded images, measure both the initial viewport and a separate run that scrolls through the content.

For example, after classifying the largest entries in the Network panel, a mobile landing page might have the following breakdown (1 KB = 1,000 bytes).

Resource groupCold loadWarm load
HTML40 KB12 KB
Images1,240 KB80 KB
Scripts320 KB35 KB
Styles and fonts100 KB10 KB
Total1,700 KB137 KB

Images account for 1,240 of the first visit’s 1,700 KB in this example. Even eliminating every script would save less than cutting the images in half.

If repeat visits continue to transfer the same assets, review our guide to Cache-Control and ETags before changing cache lifetimes. Personalized responses and versioned static assets should not necessarily follow the same policy.

Turn bytes into a useful performance budget

Suppose your first-visit report shows 1,700,000 bytes. At a sustained 4 Mbps, transferring that amount takes approximately 3.4 seconds under ideal conditions:

seconds = bytes * 8 / bits_per_second
        = 1700000 * 8 / 4000000
        = 3.4

This is a transfer-only estimate. DNS, TLS, request scheduling, congestion, rendering and JavaScript execution can make the page take longer. Requests can also overlap, so adding all resource durations together does not produce the total loading time.

Use the file transfer time calculator to compare target connection speeds and avoid mixing megabits per second with megabytes per second.

For a small editorial site, an initial budget could be 800 KB of reported transfers on a cold mobile load. Split the budget into images, scripts, fonts and everything else. Treat this as a project-specific goal, not a universal web standard. Track separate budgets for heavier application routes and for user-initiated downloads.

Make changes in order of impact

Start with the largest avoidable transfers. If a 1 MB desktop image is downloaded on a narrow screen, replacing a few hundred bytes of HTML will barely move the total. Our responsive images tutorial explains how to select appropriate image candidates with srcset and sizes.

Next, look at unused JavaScript, duplicate libraries and fonts with unnecessarily large character sets. Remove requests where possible rather than simply compressing their responses.

HTML optimization is still worthwhile, particularly when templates contain repeated markup. Try the HTML minifier on a representative copy of the document, then measure the compressed HTTP response and verify that the optimized page behaves identically.

Finally, compare user experience metrics as well as bytes. A smaller page can still feel slow if it runs expensive JavaScript before responding to input. Inspect Largest Contentful Paint and interaction responsiveness independently.

Keep the audit repeatable and private

Save a report before each substantial optimization and rerun the same test afterwards. Compare the number of unmeasurable entries as well as the totals, since otherwise adding an opaque third-party resource could make the apparent page weight smaller.

If you adapt the script for production monitoring, collect aggregate measurements instead of full resource URLs. Even a pathname can contain an account identifier or confidential document name. Establish appropriate consent, retention and sampling policies before sending browser measurements to a server.

For further details, consult the Resource Timing API reference.

Premium is coming soon

An optional premium subscription to remove ads is planned. Subscriptions are not available yet.

You can keep using our free tools without an account.