IntermediateLesson 11 of 126 min read

Performance: Page Weight, Compression and Not Doing Work Twice

Measure what a page costs to download, see how gzip compression shrinks text assets, work out image sizes, set a page-weight budget, and use debouncing to stop code from running too often, with compression sizes checked in two languages.

In this lesson you will

  • Measure page weight
  • See what compression saves
  • Calculate image memory
  • Debounce frequent events

About 28 minutes

A slow page loses visitors

On a phone in the queue, with a weak signal, Ravi’s page took eight seconds to appear, and people gave up. Speed is a feature. Two kinds of cost matter. The first is network cost: every byte must be downloaded, so total page weight and the number of requests count. The second is processing cost: after the download, the browser must parse, style, lay out and run the page, and long-running JavaScript makes it feel frozen. The best way to be fast is to send less: fewer assets, smaller assets, and nothing that is not used.

Three techniques give the biggest wins. Compression: text assets such as HTML, CSS and JavaScript contain a lot of repetition, and gzip or brotli, enabled on the server, typically shrinks them to a fraction of their size. Image choices: images are usually the heaviest part, so use the right dimensions and a modern format, and add loading=”lazy” to images below the fold. And discipline: a performance budget, a limit that your build checks, such as “total page weight below 500 kilobytes”, keeps the page from growing slowly until it is slow. In code, events such as scroll and typing can fire dozens of times a second, so a debounce function waits until the events stop before running an expensive handler.

const zlib = require('zlib');
const rows = []; for (let i = 0; i < 120; i++) rows.push('<li class="item item-' + (i % 5) + '"><a href="/bread/' + i + '">Loaf number ' + i + '</a><span class="price">' + (2 + (i % 7) * 0.5).toFixed(2) + '</span></li>');
const html = '<ul class="menu">' + rows.join('\n') + '</ul>';
const css = Array.from({ length: 40 }, (_, i) => '.item-' + (i % 5) + ' .price:nth-child(' + (i + 1) + ') { color: #8b4513; padding: ' + (i % 4) + 'px; margin: 0 auto; }').join('\n');
function sizes(name, text) {
  const raw = Buffer.byteLength(text), gz = zlib.deflateSync(text, { level: 9 }).length;
  return { name, raw, deflate: gz, saved: Number(((1 - gz / raw) * 100).toFixed(1)) };
}
const out = [sizes('html', html), sizes('css', css), sizes('random-like', (() => { let s = 12345, o = ''; for (let i = 0; i < 4000; i++) { s = (s * 16807) % 2147483647; o += String.fromCharCode(33 + s % 94); } return o; })())];
out.forEach(o => console.log(o.name.padEnd(12), 'raw', String(o.raw).padStart(6), ' deflate', String(o.deflate).padStart(6), ' saved', o.saved + '%'));
const img = (w, h) => ({ w, h, decodedKB: w * h * 4 / 1024 });
const big = img(4000, 3000), shown = img(800, 600);
console.log('decoded photo 4000x3000 uses', Math.round(big.decodedKB), 'KB of memory; 800x600 uses', Math.round(shown.decodedKB), 'KB; ratio', (big.decodedKB / shown.decodedKB).toFixed(1));
function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }
let calls = 0, last = null;
const search = debounce(q => { calls++; last = q; }, 50);
for (const q of ['s', 'so', 'sou', 'sour', 'sourd']) search(q);
setTimeout(() => { search('sourdough'); }, 120);
setTimeout(() => {
  console.log('10 keystroke-like calls in two bursts ran the handler', calls, 'times; last value:', last);
  console.log('DATA ' + JSON.stringify({ out, big: big.decodedKB, shown: shown.decodedKB, calls, last, html, css }));
}, 300);
html         raw  11921  deflate    934  saved 92.2%
css          raw   3150  deflate    264  saved 91.6%
random-like  raw   4000  deflate   3334  saved 16.6%
decoded photo 4000x3000 uses 46875 KB of memory; 800x600 uses 1875 KB; ratio 25.0
10 keystroke-like calls in two bursts ran the handler 2 times; last value: sourdough

The generated menu page of 120 items is 11,921 bytes of HTML, and compression with the deflate algorithm, which gzip uses, brings it down to 934 bytes, a saving of 92.2%. The repetitive CSS saves 91.6%: 3,150 bytes become 264. The third sample, text with little repetition, saves only 16.6%, which shows that compression works by finding repeats, and that text, markup and code compress well, while images and videos, which are already compressed, do not. The server must be configured to apply it, so check your hosting documentation, and remember that brotli usually compresses a little better than gzip.

The image arithmetic shows why photos hurt. A decoded image uses four bytes per pixel in memory whatever its file size, so a 4000 by 3000 photo needs about 46,875 kilobytes, even if the file is only a few hundred kilobytes, while the 800 by 600 version that the page actually displays needs 1,875: 25 times less. Resize images to the size you display, at most twice that for sharp screens. The debounce test shows the third technique: ten calls in two bursts, five in a quick series and one later, called the handler 2 times, the last with “sourdough”, because each new call cancelled the waiting one until 50 milliseconds had passed in silence.

Independent check: Python’s zlib, called with the same compression level on the same text, produced exactly the same compressed sizes as Node’s zlib for the HTML and the CSS, because both use the same algorithm. The size of a real gzip file is 18 bytes more than the raw deflate stream, for the header and the checksum trailer, which is small enough to ignore. The decoded image sizes are plain arithmetic, 4000 x 3000 x 4 / 1024 = 46,875.

Check by hand: 800 x 600 x 4 = 1,920,000 bytes, which is 1,875 kilobytes, and 4000 x 3000 x 4 = 48,000,000 bytes, or 46,875 kilobytes, which is 25 times as much because the area is 25 times larger.

Do not optimise without measuring

Measure first, with the performance tools of your browser or an audit tool, and fix the biggest problem. Guessing wastes time and often makes code harder to read.

Set a budget

Write the budget down, such as “under 500 KB total and under 50 requests on a phone”, and check it whenever you add something. A page rarely becomes slow in one step.

About this course

Every program in this lesson was run while the course was written, with Node.js 22, jsdom 31 (a pure-JavaScript DOM used for tests, not a real browser) and Python 3.13. Browsers, tools and their menus change often, so check the official documentation (MDN, the Node.js docs, your provider) for current behaviour. Compression ratios depend on the content. The numbers here are for the generated sample files and are not a promise for your site.

Practice

Compress your own HTML file and note the saving. Calculate the memory of the largest image of your site. Write a throttle function that runs at most once every 100 milliseconds and test it with ten rapid calls.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does compression exploit?

  1. Colours
  2. The server speed
  3. JavaScript
  4. Repetition in the data

Text compresses well.

Why do large photos hurt even if the file is small?

  1. They are slow to type
  2. They block CSS
  3. A decoded image needs four bytes per pixel in memory
  4. They break HTML

Resize to the displayed size.

What does debounce do?

  1. Runs the handler on every call
  2. Cancels the page
  3. Waits until calls stop before running the handler once
  4. Compresses the data

Good for search boxes and scroll.

What is a performance budget?

  1. A salary
  2. A limit that your build checks
  3. A server price
  4. A CSS rule

Stops slow growth.

Which assets compress poorly?

  1. HTML
  2. Already compressed images and video
  3. CSS
  4. JavaScript

JPEG and MP4 are compressed already.

Summary

  • Send less: fewer, smaller assets.
  • Compression shrinks repetitive text dramatically.
  • Images cost memory by pixels, not by file size.
  • Debounce frequent events and keep a performance budget.

Next lesson

Lesson 12 is a capstone: the finished bakery page.

Questions

Is gzip or brotli better?

Brotli usually gives smaller files, and both are widely supported. Many hosts enable them for you, so check your provider's documentation.

What is lazy loading?

Delaying the download of images below the visible area until the visitor scrolls near them, with loading="lazy" on the img element.

How do I measure page speed?

Use the performance panel of your browser's developer tools, or an audit tool such as Lighthouse, and test on a slower network, because your own connection is probably faster than your visitors'.

Progress is saved in this browser.