NiceDay

Does deferring AdSense make your site faster? 48 measured page loads

A few days ago I did a round of performance work on this site aimed squarely at ads: I pulled the AdSense script out of the page and loaded it only after the page had finished loading and the main thread was idle. In other words, I deferred it. The commit message gave the reason: ads were pushing the load event out to about 15 seconds.

Before writing this, I re-measured three versions (before the change, after it, and with no ads) across 48 loads. The verdict: the change didn't make the page appear any sooner. It wasn't wasted either; it just did something other than what I thought. Re-measuring turned up a few numbers more interesting than "did the optimization work": the part of this home page I actually wrote is only 7.6KB, yet every visit downloads 262KB; in the 32 loads with ads that I measured, an ad was never displayed once; and by a different metric, the first thing that stalls the page is my own page.

If you also run ads, or are about to defer some third-party script, here's what you can take away:

  • A detection script. A dozen or so lines you paste into the browser console. It shows how soon text appears and who caused each long frame.
  • A verdict. What deferring a third-party script can and can't do, and on which networks it pays off.
  • A checklist. Five things to confirm before running ads. I tripped over every one.

Conclusions first, then how I got it wrong.

The verdict: the page is tiny, the ads are heavy, and deferring only changed load

  • Transferring the page isn't the problem. The HTML is 7.6KB compressed and arrives in one round trip. From first byte to text on screen: a median of 0.14 to 0.18 seconds on desktop, 0.27 to 0.42 seconds on a throttled phone.
  • The ads are what's heavy. The AdSense script brings 236KB, 6 third-party requests and two long tasks, and accounts for 70% of script execution time.
  • The one thing deferring definitely did: the load event fires earlier. On a throttled phone it went from 2.44 to 0.99 seconds; on a narrow connection, from 6.6 to 1.2 seconds. On desktop broadband, nothing changed.
  • What it didn't do: first paint is no faster; not one downloaded byte was saved; not one of the two long tasks went away, they just happen at a different time; and everything finishes downloading later than before.
  • And three things I didn't expect before measuring. That 15 seconds referred to the load event, not when the page becomes visible; in 32 loads with ads, an ad never displayed once; and the page's own first frame contains a 108 ms long task that the observer I was using to count long tasks never reported.

How that last one surfaced starts with how I measured. Half the lesson this time was in the method.

How I measured: three versions, four networks, and a script you can use too

I measured the live site with headless Chrome 157: cold cache and a fresh browser profile every time, taking the median of 3 to 5 runs per combination. Three versions: before, with a <script async> loading the ads straight from the head; current, with the ads inserted by /app.js after load; and no ads, with that meta tag removed. The old setup was reproduced without touching live code, by inserting the tag back in as soon as the document started parsing. Four networks: desktop unthrottled; phone, Lighthouse's default mobile settings of 1.6 Mbps down, 150 ms per request and CPU slowed 4x; a bad network, with an extra 600 ms per request; and narrowband, with downlink squeezed to 400 kbps.

These numbers are optimistic or uncertain in three ways. First, CPU: emulating 4x slowdown on Apple Silicon is probably still faster than a mid-range phone. Second, location: my machine wasn't on a proxy, but my router splits traffic and my public exit is in Hong Kong, so Cloudflare served me from its Hong Kong data center and my first byte arrived sooner than it would for most visitors. Third, whether ads get served at all: the headless browser, the fresh profile and this exit point could all affect the ad system's decisions. So these numbers are good for comparing the three versions, not for claiming "real users see it in 0.6 seconds".

The first version of my measurement script was also broken: it reported zero ad requests for all three versions, and I very nearly wrote this post around a table full of zeros. A measurement only counts once you've looked at it yourself.

To measure it yourself, you don't need a script. Two steps are enough.

Step one: make the comparison, and see how much gets pulled in. Open Chrome DevTools, open the Request conditions drawer under More tools (or search for it by name in the command menu), add the ad domains to block them, and reload with DevTools open. That's your "no ads" version. Put the two Network panels side by side, and the group-by-domain view gives you the ads' request count and bytes.

Step two: see who's stalling. Once the page has finished loading, paste the snippet below into the console. It needs Chrome or Edge 123 or later. It reads entries the browser has already recorded, so it doesn't affect the load you're measuring.

(async () => {
  const ms = n => Math.round(n) + 'ms';
  const nav = performance.getEntriesByType('navigation')[0];
  const fcp = performance.getEntriesByType('paint').find(e => e.name === 'first-contentful-paint');
  const name = s => (s.sourceURL || '(this page)').split('/').filter(Boolean).pop();
  const grab = type => new Promise(done => {
    let hit = false;
    const o = new PerformanceObserver(list => { hit = true; done(list.getEntries()); });
    o.observe({ type, buffered: true });
    setTimeout(() => { if (!hit) done(o.takeRecords()); }, 1000);  // with no long frames the callback never fires, so fall back after 1 s
  });
  const [lcp, frames] = await Promise.all([grab('largest-contentful-paint'), grab('long-animation-frame')]);
  console.log('First paint', ms(fcp?.startTime), '| Largest content', ms(lcp.at(-1)?.startTime ?? 0), '| load', ms(nav.loadEventEnd));
  console.log('Long frames over 50 ms:', frames.length);
  for (const f of frames) {
    const who = f.scripts.map(s => name(s) + ' ' + ms(s.duration)).join(' + ');
    console.log('   ', ms(f.startTime), 'lasting', ms(f.duration), 'from', who || 'rendering and style, not script');
  }
})();

Pasted into my home page on a throttled phone, it prints:

First paint 424ms | Largest content 424ms | load 669ms
Long frames over 50 ms: 3
    259ms lasting 152ms from rendering and style, not script
    1244ms lasting 73ms from adsbygoogle.js 71ms
    2563ms lasting 93ms from show_ads_impl.js 87ms

I had it count long frames rather than the more familiar "long tasks", and that's the single most important choice in this script. Long tasks don't include rendering work like style calculation and layout; Chrome's documentation calls them an incomplete view. Long frames cover the whole frame, rendering included. So you'll see one or two more long frames than long tasks, and the extra one is often the page itself.

One more limitation: work inside cross-origin iframes can't be attributed. If anything, the ads' share is understated.

When I pasted this script into my own home page, the first thing it flagged wasn't the ads.

A 7.6KB page, and its first frame still takes over 100 ms

It's the first line of the output: at 259 ms, a 152 ms long frame "from rendering and style, not script". It's there with or without ads, at 110 to 150 ms in most measurements. To see what that frame was doing, I recorded a browser trace of the no-ads version: 10 ms parsing HTML, 35 ms of style calculation, 53 ms of layout, 13 ms preparing to paint, all in a single main-thread task of 108 ms. The frame runs a bit longer than the task because other small tasks in the same frame count toward it. My own /app.js ran for only 5 ms in the whole load and has nothing to do with it.

On a post page with no ads, the same script counted 4 long frames in one run: two of the page's own style and layout at 214 and 186 ms, and one from Cloudflare's analytics script at 68 ms. "No ads, no stalls" doesn't hold even on my own site.

So "the page is fine" was only half right. Transfer really is fine, but the single task of drawing the first screen takes over 100 ms. More worth noting is that I hadn't seen it. In those 48 runs I was counting long tasks, and the no-ads version had zero. Long tasks ignore style and layout, so for the same page they say 0, a whole-frame script says 1, and the trace shows a 108 ms task. Which metric you use decides which problems you can see.

Now the half that was right, and where the 7.6KB comes from. The stylesheet is inlined, 2.6KB compressed, about a third of the total; the rest is content, structured data for search engines, and a 280-character theme script. There are no images on the page; the logo is an inline SVG. There are no custom fonts, only system fonts. There are no render-blocking external files: the only script, /app.js, is deferred and 5.7KB over the wire. Everything needed to draw the first screen arrives in one request.

The site has no build step, either. I measured what that costs: stripping all line breaks and indentation from the stylesheet saves just 25 bytes compressed, and stripping all the Chinese comments from /app.js saves 0.6KB after gzip. I kept the comments. I wrote about how the page is put together when I split out the Worker.

Exactly what's expensive in there, I haven't dug into yet; that's in the questions at the end. This frame has nothing to do with ads; it's there either way. What really comes with the ads is in the next section.

One AdSense script tag, 236KB downloaded

The ad entry point is just one <script async>, 56KB. When it runs, it pulls in a second script, 166KB, which it inserts with fetchpriority="high" set on itself. After that come two hidden iframes pointing at doubleclick, a config request (14KB), and then sodar2.js. One tag, with five requests trailing behind it, each waiting on the last.

No ads26KBNowSite 16KBStats 10KBAd loader56KBSecond ad script, show_ads_impl166KB262KBOther 14KBAds: 236KB, 9× the page + analytics (26KB).
How much one home page visit downloads. Throttled phone, cold cache, median.

For every visit to the home page, nine-tenths of what gets downloaded isn't mine. The CPU tells the same story: on a throttled phone, total script execution time rises from 44 ms to 140–150 ms, 70% of it the ads. The long-task observer reports 0 without ads and 2 with ads, totaling a bit over 160 ms. As I said, that 0 is the observer missing the page's own task; the two the ads add are real.

By now you're probably wondering: after downloading all that, what actually shows up on the page?

Nothing. The ad container ins.adsbygoogle is 0 by 0 with display: none, and so are both iframes. In 32 loads with ads, it was the same every time: the code downloaded, ran, stalled the page twice, and no ad ever appeared. I'm not sure why. Maybe the headless browser was detected, maybe a fresh profile has no history, or maybe there's simply no inventory for this exit location. Whether real visitors see the same thing, I'd have to check against impressions in the ad dashboard.

Its size isn't fixed, either. The commit message says about 685KB; the first time I measured, 236KB. Less than an hour later, the same two scripts at the same URLs had gone from 56KB and 166KB to 66KB and 189KB. A dozen minutes after that, the domain wouldn't connect at all from my network, and the script tag hung for 15 seconds without a response. How big a file it returns, or whether it returns at all, isn't up to me.

So before the change, every visitor's browser was running these 236KB, stalling twice, and showing nothing. My change pushed all that later. What did that buy?

Deferring the ad script: load fires earlier, first paint doesn't move

The only difference before and after is one line in the head. It used to be a <script async> loading the ads; now it's a <meta name="google-adsense-account"> that only verifies site ownership, and /app.js inserts the script after load.

The logic in /app.js: wait for the page's load event, then wait for the main thread to go idle, and only then create the script tag and insert the ads. Browsers that support requestIdleCallback wait up to 4 seconds; those that don't wait a fixed 1.5 seconds. That 4 seconds is a fuse: however busy the main thread, the ads come in no later than 4 seconds after load.

Here's how the three versions behave on a throttled phone; each point is the median of 5 loads.

Oldload 2.44 sdone 2.75 sLazyload 0.99 sdone 3.94 sNo adsload 0.70 sdone 0.95 s01 s2 s3 s4 sTitleTab spinningAd long task (≥50 ms block)
Throttled phone: 1.6 Mbps down, 150 ms latency per request, CPU slowed 4x. Cold cache, each point the median of 5 loads. The long tasks marked come from the ad scripts running; the one in the page's own first frame wasn't reported by the long-task observer.

What it did do is make load fire earlier. Load is the moment the page and every resource it references have arrived; until then, the icon on the tab keeps spinning. In the old setup, the ads counted as "resources the page references", so the icon kept spinning until that chain of ad requests finished: 2.44 seconds on a throttled phone, 4.54 on the bad network, 6.61 on narrowband. Deferred, the ads don't count, and the icon stops at around 1 second.

That gain is tied to network quality. The ad requests run one after another, so the higher the latency and the narrower the bandwidth, the longer load gets dragged out and the bigger the payoff from deferring: 1.4 seconds between the two setups on a throttled phone, 3 seconds on the bad network, 5.4 seconds on narrowband. Conversely, on unthrottled desktop, load is 0.69 seconds in both the old and new setups. On broadband, this change gained nothing.

Three things it didn't do.

First, first paint got no faster. The three hollow circles in the chart sit almost on one vertical line: 0.58 seconds for the old setup, 0.74 deferred, 0.59 with no ads. The ranges across 5 loads overlap, so you can't tell which is faster. The reason isn't hard to see. The old setup also used async, so the browser starts drawing as soon as the HTML arrives, without waiting for ads; and the page is only 7.6KB, which transfers in 150 ms even on narrowband, so the ads can't crowd it out. I'd guessed that on narrowband the ads would compete with the page for bandwidth and added a 400 kbps set of measurements specifically to check, but text still appeared at 0.8 to 1.0 seconds in all three versions.

Second, the ad scripts' long tasks didn't decrease. Both versions have two, totaling just over 160 ms. All that changed is when they happen: 0.4 and 1.55 seconds after the title in the old setup, 0.75 and 1.9 seconds when deferred.

Third, everything didn't finish downloading any sooner. On a throttled phone it actually finished 1.2 seconds later, going from 2.75 to 3.94 seconds, because the ads went from "downloading alongside the page" to "queued behind the page". Same bytes, different order.

If first paint never got faster, where did the 15 seconds in the commit message come from?

The load event and first paint are two different things

The 15 seconds came with half a sentence more: the commit message said "tested through a proxy". On my usual network, the old setup's load was 2.44 seconds on a throttled phone, 4.54 seconds with an extra 600 ms per request, and 6.61 seconds at 400 kbps. I couldn't reproduce 15 seconds. But it may well be real for some visitors: my exit is close to the site, and for anyone far from the edge or on a network that takes detours, every bit of extra latency pushes load later. First paint is different: even on the bad network, text appeared at 0.9 to 1.1 seconds in all three versions.

So the number wasn't wrong, but it was easy to read as something else: 15 seconds measured how long the icon spun, not how long until the page was visible. I got the direction of the optimization right, but my sense of how big the problem was and who it helped was off the whole time.

The change wasn't wasted; it just solved a different problem from the one I thought. The same round of changes included three more things whose costs I only saw in hindsight.

Link prefetching, caching, and a typewriter animation: what each costs

Link prefetching. Chromium supports a declaration called speculation rules: you put it in the head, and the browser fetches a page ahead of time when you hover over or press an internal link. I only let it prefetch HTML, not prerender. Browsers that don't support it fall back to /app.js, which puts the page in the cache with a low-priority fetch and skips devices in data-saver mode. There's a detail I didn't read closely when writing the rule: it says "eagerness": "moderate", which according to Chrome's documentation means "hover for 200 ms or press" on desktop. Phones have no hover, so the browser guesses instead, prefetching several large-enough links nearby half a second after scrolling stops. I measured it 3 times on a post page, and once, 6 seconds after the page opened, without my tapping anything, the browser fetched two extra pages. At a dozen KB per page it doesn't matter; on a site with hundreds of KB per page, it's spending the user's data for them.

Caching. The URL of /app.js carries a version number derived from the file's contents, so it changes whenever the contents do, which makes it safe to cache as immutable for a year. HTML is cached for 5 minutes, plus an hour of stale-while-revalidate. The cost is that anyone returning within 5 minutes of a deploy gets the old page.

The typewriter animation. The home page has a line of text that types itself out in a loop, updating every 110 ms. Each update triggers a round of style, layout and paint: in the trace, the 5.6 seconds after the first frame had 79 style recalculations, 109 ms across the whole rendering pipeline, about 2% of the main thread. Each one is under 1 ms, so it never shows up as a stall, but it's always running. Now it stops when it scrolls out of view or the tab is in the background. This change got one line in the commit message, yet it's the only one of the changes that actually made the browser do less work.

Those three are at least trade-offs. The next one isn't; it's my mistake.

Content Security Policy: how much is left once you add ads

This site's CSP opens with default-src 'none': allow nothing by default. Sounds strict. I can count exactly two things it has actually blocked so far, and both were on my own side.

The first was Cloudflare's analytics script. Cloudflare automatically injects a beacon.min.js at the end of every page, 10KB over the wire, bigger than my own /app.js. It wasn't on the allowlist, so every page threw an error and not a single page view or load-speed measurement was recorded. The pages looked completely normal, so if not for the error in the console, it would have stayed silent forever. I later allowed it and added a line to the privacy policy.

The second is sodar2.js, the next script the ad script itself loads. The allowlist had googlesyndication.com, doubleclick.net, google.com and gstatic.com, but not adtrafficquality.google, where it lives. Every load with ads logs an error for it in the console, next to an uncaught exception from the ad script. That one is still there; I haven't touched it.

And one thing that isn't a block but a non-block. To let the ads run, frame-src and connect-src are set to https:, so any HTTPS site can open an iframe or send requests from this page; styles use 'unsafe-inline'. The only truly strict part left is scripts, and five of the domains it allows are there for ads. What it actually blocked was the analytics script and a domain the ad vendor itself left out. The phrase "I set default-src 'none'" gave me more sense of security than it actually provided.

That's everything I needed to own up to. Here are the parts of this post you can use directly.

A checklist to take with you: five things to confirm before running ads

  1. Is the ad actually displaying? After the page loads, run the line below in the console. If width and height are both 0, it isn't. Then check impressions in the ad dashboard. All 32 of my measurements were 0.
    document.querySelector('ins.adsbygoogle')?.getBoundingClientRect()
  2. How many bytes and requests does it pull in? Paste the script above, or check the Network panel grouped by domain. Mine accounted for nine-tenths, and the size changed within an hour.
  3. How many long frames does it bring? Look at the lines in the script's output where "from" is followed by a .js file. Mine had two, 60 to 90 ms each.
  4. Are you measuring load or first paint? They're not the same thing, and deferring can only move the first.
  5. Are there CSP errors in the console? If so, your allowlist is incomplete. Mine logs one every time and still isn't fixed.

If you've already decided to defer a third-party script, remember three things: it can make load fire earlier, but it can't save bytes or long frames; the only way to save those is not to include it. The gain is tied to network quality and is zero on desktop broadband. And verify ownership with the meta tag; don't leave the script in the HTML, or it counts toward load again.

The checklist covers the problems I already know about. Below are five I haven't solved.

Five questions I haven't figured out

  1. Are the ads doing anything at all? I measured 32 times and they never displayed. The code comments record how big they are; nothing anywhere records whether they appeared. Have you confirmed that the heaviest thing on your page is actually working?
  2. Does a long frame that moved count as fixed? Deferring cleared the first 0.4 seconds after the title appears, at the cost of moving the stalls to 0.75 and 1.9 seconds, right about when people start scrolling. Did I solve the problem, or move it to a moment I don't look at?
  3. Why does the first frame take 108 ms? 35 ms of style calculation, 53 ms of layout across 251 layout objects, with the CPU slowed 4x. The first screen has only 489 DOM nodes and a 135-line stylesheet, no images and no custom fonts. Which rules and which part of the layout cost the most, I haven't dug into yet. How long does your page's first frame take?
  4. How often should a "measured" number be measured again? The 15 seconds sat in the commit history for six days, and I never questioned it because it had been measured. On a different network, it's 2.4 seconds. Even the ad script's own size changed by more than 10% in under an hour. When did you last go back and verify the before-and-after numbers of your own optimizations?
  5. Is 7KB worth a whole post? The part I control is just 6% of what visitors actually download, and within that 6% there are still 100 ms of style and layout to investigate. I've said before that development is only 1% of the work, and this is the same point: squeezing 7.6KB down to 7KB matters less than simply removing the other 90%, but that 90% is something I put there to earn money. How much load time and how many stalls should an indie developer trade for an ad impression that may never even happen? I haven't worked out that math, because I don't even know yet whether the ads are being shown.

If you also run AdSense, paste the script above into your page and run it. Whether your results match mine or not, I'd like to know; you can write to me.

— NiceDay