Two tiny attributes that speed up a page
Alongside a big bundle cut, two one-line changes helped our payment page start faster on phones. What defer and preconnect do, and when to use them.
The biggest win on our payment page that month was removing an 80 KB library. But two one-line changes in the HTML helped too, and they’re worth knowing because they work on almost any site.
1. defer: stop scripts from blocking the page
When a browser builds a page from HTML and meets a plain <script src="…">, it stops. It downloads the script, runs it, and only then carries on reading the HTML. Every script in the page’s head is a pause before the customer sees anything.
defer changes that:
<script src="/loader.js" defer></script>
With defer, the browser downloads the script in the background while it keeps building the page, and runs it once the HTML has been read. Deferred scripts still run in the order they appear, so scripts that depend on each other keep working.
Use it when a script doesn’t need to run before the page is built, which is most of them. Watch out if a script writes to the page while it loads, or if other code expects it to have run immediately.
Its sibling, async, also downloads in the background but runs each script the moment it arrives, in any order. That suits independent scripts like analytics, not scripts that depend on each other.
2. preconnect: start the conversation early
Before a browser can download a font from another domain, it has to find the server, connect and set up a secure connection. On a phone, that can add up to hundreds of milliseconds, and normally it only starts once the browser discovers it needs the font, partway through loading the page.
preconnect asks the browser to start that work right away:
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
By the time the page asks for the font, the connection is ready.
Use it for one or two third-party domains you’re certain to need early: fonts, a payments API, an image CDN. Don’t overdo it. Every preconnect costs the browser some work, and connections it opens but doesn’t use are wasted. The crossorigin attribute matters for fonts, because fonts are fetched in a way that needs it, or the early connection can go unused.
The pattern
Both changes are about order, not size. They don’t make anything smaller. They let the browser start useful work sooner instead of waiting. On a payment page, where the first second decides whether a customer trusts you, that ordering is worth a look before anything else.
The other quiet win was removal: a sanitiser library and some files the page no longer used. Deleting code is the one optimisation that never needs a benchmark to justify it.