Page Speed in Practice: Compression, Caching and Fewer Requests
Find where page time goes and fix it with three ideas: send less, send it once and send fewer things, measured with a real local server.
In this lesson you will
- See where page time goes
- Compress and minify text files
- Understand caching and 304
- Test and change one thing at a time
About 19 minutes
The speed plugin nobody understood
Dina’s craft-supplies shop sits on cheap shared hosting, and her pages feel slow. A friend told her to install a speed plugin. She switched on every option she could find, the site broke twice, and she still cannot say whether it got faster. The tool did not fail her. She just did not know which problem she was solving. This lesson explains where page time goes and the three ideas behind nearly every speed fix: send less, send it once, and send fewer things.
Where the time goes
When someone opens your page, three things happen. First the server builds and sends the page, which depends on your hosting. Then the browser downloads everything the page needs: styles, scripts, fonts and images. Finally the browser works out how to draw it all. You can improve each stage, but beginners get most of their gains from the second, which is mostly about how many bytes travel and how often.
Idea 1: send less
- Compress text files. Servers can squeeze HTML, CSS and JavaScript before sending, and browsers unpack them automatically. The most common method is called gzip, and an alternative called Brotli is also common.
- Minify files. Minifying removes spaces, line breaks and comments from code that a browser does not need.
- Shrink images. Lesson 8 showed that resizing and compressing images is the biggest saving of all.
Idea 2: send it once
A visitor who comes back should not have to download your logo and stylesheet again. Caching lets the browser keep a copy. A response header called Cache-Control says how long the copy is good for. A second header, the ETag, is a fingerprint of the file. When the browser asks again it can say, ‘I have the version with this fingerprint’, and if nothing changed the server answers with a tiny 304 reply that means ‘use your copy’. No file is sent at all.
Idea 3: send fewer things
- Remove plugins, scripts and fonts you do not use. Each one is more to download.
- Load images lower down the page only when needed (lazy loading, lesson 8).
- Keep third-party add-ons such as chat widgets and trackers to the ones you truly need.
Measure it for real
The program below starts a small web server on your own computer and serves a stylesheet of 200 rules. Then it asks for the file four ways: plain, with gzip, minified, and as a repeat visit that sends the fingerprint. The sizes are bytes actually received. The stylesheet is machine-made and very repetitive, so it squashes more than most real files would. Use it to see the idea, then test your own files. We checked every number again with a different compression call and with curl.
import gzip, hashlib, http.client, re, threading
from http.server import BaseHTTPRequestHandler, HTTPServer
colours = ["#14112E", "#5A28C8", "#4A6EDD", "#46D3DC", "#F06CC2", "#6C2BE0"]
kinds = ["card", "btn", "nav", "hero", "tab", "tag", "box"]
css = "\n".join(
f".{kinds[i % 7]}-{i} {{\n margin: {i % 9}px auto;\n padding: {8 + i % 5 * 4}px {12 + i % 11}px;\n"
f" color: {colours[i * 5 % 6]};\n border-radius: {i % 13 + 2}px;\n}}"
for i in range(200))
raw = css.encode()
etag = '"' + hashlib.md5(raw).hexdigest()[:12] + '"'
class Site(BaseHTTPRequestHandler):
def do_GET(self):
if self.headers.get("If-None-Match") == etag:
self.send_response(304)
self.send_header("ETag", etag)
self.end_headers()
return
body, zipped = raw, "gzip" in self.headers.get("Accept-Encoding", "")
if zipped:
body = gzip.compress(raw)
self.send_response(200)
self.send_header("Content-Type", "text/css")
self.send_header("Cache-Control", "max-age=86400")
self.send_header("ETag", etag)
if zipped:
self.send_header("Content-Encoding", "gzip")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Site)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
def get(extra):
conn = http.client.HTTPConnection("127.0.0.1", port)
conn.request("GET", "/style.css", headers=extra)
r = conn.getresponse()
data = r.read()
conn.close()
return r.status, len(data), r.getheader("Content-Encoding")
s1, plain, _ = get({})
s2, zipped, enc = get({"Accept-Encoding": "gzip"})
s3, empty, _ = get({"If-None-Match": etag})
mini = re.sub(r"\s+", " ", css).replace("{ ", "{").replace("; ", ";")
print(f"Plain: {plain} bytes")
print(f"Gzip ({enc}): {zipped} bytes, {100 * (1 - zipped / plain):.0f}% smaller")
print(f"Minified: {len(mini.encode())} bytes")
print(f"Minified + gzip: {len(gzip.compress(mini.encode()))} bytes")
print(f"Repeat visit with ETag: status {s3}, {empty} bytes")
server.shutdown()
Plain: 20582 bytes
Gzip (gzip): 2027 bytes, 90% smaller
Minified: 16382 bytes
Minified + gzip: 1946 bytes
Repeat visit with ETag: status 304, 0 bytes
The plain file is 20,582 bytes. With gzip it is 2,027 bytes, 90% smaller. That is the biggest single win, and most hosts can switch it on for you. Minifying alone cut the file from 20,582 to 16,382 bytes (20% less). But compare the fourth line with the second: minified plus gzip is 1,946 bytes against 2,027 for gzip alone, only 4% better. Gzip already removes most of the repetition that minifying targets. So turn on compression first, and treat minifying as a smaller extra.
The last line is the caching result. On a repeat visit with the fingerprint, the server replied with status 304 and 0 bytes. The file was not sent at all. For a site where most visitors return, that is a large saving across thousands of requests.
Cache safely
Long cache times have one danger. If you change a stylesheet but visitors keep the old copy, they see a broken or outdated page. The fix is to change the file name or add a version number when the file changes, for example style.css?v=7. Good platforms and caching tools do this for you. Keep long cache times for files that rarely change, such as images and fonts, and short ones for pages.
Measure the whole page
Free tools such as PageSpeed Insights, the Lighthouse panel in Chrome and WebPageTest test real pages and list what to fix, in order of impact. They run on the web or in a browser, so they were not run for this lesson. Test on a phone-sized setting, change one thing at a time and test again. Google publishes target values for its page-experience measures, which can change, so check web.dev for the current ones.
Switching on every optimisation at once. If something breaks you will not know which setting did it. Change one thing, test the page, then move on.
On WordPress, compression and caching often come from your host or from a caching plugin. Use one caching tool at a time, since two can conflict, and test your forms, shop and login after any change.
Practice for this lesson
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What are the three speed ideas in this lesson?
- Paint, print, publish
- Copy, paste, delete
- Buy, sell, rent
- Send less, send once, send fewer things
Compress and shrink, cache, and reduce the number of requests.
What does a 304 status mean?
- Page not found
- Use your saved copy
- Server broken
- Moved for good
The file has not changed, so the browser can reuse its copy and nothing is downloaded.
In the demo, which saved the most space?
- Minifying alone
- Renaming the file
- Gzip compression
- Adding comments
Gzip cut the sample file by about nine tenths, far more than minifying alone.
Why is the demo stylesheet not a fair guide to real files?
- It is machine-made and repetitive
- It is too small
- It has no colours
- It was minified twice
Very repetitive text compresses unusually well. Test your own files.
How do you stop visitors keeping an old stylesheet?
- Delete the page
- Shorten the title
- Change the file name or version
- Turn off images
A new name or version number makes browsers fetch the new file.
Summary
- Send less by compressing, minifying and shrinking images.
- Send it once with caching headers and fingerprints.
- Send fewer things by removing what you do not use.
- Change one thing at a time and test again.
Questions
Do I need to minify if I use gzip?
It helps a little, but compression gives most of the saving. Turn on compression first, and minify if your platform makes it easy.
Will a caching plugin fix a slow site?
It can help a lot with the time to build pages, but a site with huge images or too many scripts will still be slow. Find the real causes with a speed test first.
Is a CDN worth it?
A content delivery network serves your files from places near visitors, which helps sites with an international audience. For a purely local site it is usually a small gain. Check your host, which may include one.
