Cutting 960 ms of Total Blocking Time by Not Loading Google Tag Manager
Lighthouse blamed our site's Total Blocking Time on tag manager and analytics, not on our own code. Deferring to window load did nothing. Firing on first user interaction took TBT to zero.
This site's mobile Lighthouse score sat at 0.78 with 960 ms of Total Blocking Time, and none of it was our code. Fixing it took one change to one script tag - but only after two wrong attempts, and only because we read the attribution audit before touching anything.
The symptom
Total Blocking Time measures how long the main thread was busy with long tasks between First Contentful Paint and Time to Interactive. On a mostly static marketing site it should be close to zero, because there is almost nothing to execute. Ours was 960 ms on the mobile run, which drags the whole performance score down hard - 0.78, in a band where the field data starts to matter.
The instinct at that point is to look at your own JavaScript. Split the bundle, defer the non-critical parts, minify harder. We have done that reflexively before and it is almost always the wrong first move, because it optimises the thing you can see rather than the thing that is slow.
Diagnosis: make Lighthouse tell you whose milliseconds these are
Lighthouse already has the answer, in two audits people skip past on the way to the score. bootup-time ("Reduce JavaScript execution time") breaks total script CPU down by originating URL. third-party-summary ("Reduce the impact of third-party code") groups the same data by vendor. Run the mobile audit and expand them before you form a theory - it is the first thing we do on any landing page handed to us.
For this site, the attribution was unambiguous:
| Script | Main-thread time |
|---|---|
| GA4 gtag | 576 ms |
| gtm.js | 419 ms |
| AdWords gtag / destination tag | 396 ms |
| The site's own JavaScript | 8 ms |
Eight milliseconds. Everything we could have done to our own code - bundling, tree-shaking, minifying, a smaller framework - was competing for a prize of 8 ms against roughly 1.4 seconds of vendor script. That table is the whole article in one image. The reason to read the audit first is not thoroughness, it is that the obvious optimisation was worth nothing.
You can get the same attribution from the command line if you would rather not click through the UI:
npx lighthouse https://example.com/ \
--preset=perf \
--form-factor=mobile \
--output=json --output-path=./lh.json --quiet
node -e "const r=require('./lh.json');
for (const i of r.audits['bootup-time'].details.items)
console.log(Math.round(i.scripting), 'ms', i.url);"
Wrong attempt one: defer GTM to the load event
The standard advice is to move tag manager out of the critical path by loading it on window's load event. We did that. TBT barely moved.
The reason is a little counter-intuitive: the site was too fast for that to help. LCP is around 1.5 s. There are no heavy images, no blocking stylesheets of consequence, no hydration step. load therefore fires very early, and gtm.js - plus the two gtag payloads it pulls in - landed squarely inside the window Lighthouse is measuring. Deferring to load moves work later on a slow page. On a fast page it moves it by almost nothing.
The second idea, conditionally skipping the tag for Lighthouse's user agent, we rejected immediately. Serving different code to a measurement tool than to users is cheating your own instrumentation, and it does nothing for real visitors, who are the only reason the metric matters.
The fix: fire on first user interaction
The insight is that analytics does not have to run during page load. It has to run before the visitor leaves. Those are very different deadlines. A visitor who is going to be counted as a session will, essentially always, do something - scroll, move a mouse, tap, press a key. So arm listeners for the cheapest possible signals, fire the tag on whichever arrives first, and keep a timer as a backstop for the visitor who does nothing at all.
This is the code that runs on this site, in the base template, in place of the standard GTM container snippet:
<script>(function(w,d,s,l,i){function g(){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
}
var fired=false;
function fire(){ if(fired){return;} fired=true; g(); evts.forEach(function(evt){ w.removeEventListener(evt, fire); }); clearTimeout(tmr); }
var evts=['scroll','keydown','mousemove','touchstart','pointerdown'];
evts.forEach(function(evt){ w.addEventListener(evt, fire, {passive:true, once:true}); });
var tmr=setTimeout(fire, 5000);
})(window,document,'script','dataLayer','GTM-WW65RPLN');</script>
The inner function g() is the unmodified GTM container snippet - the gtm.start push and the async script injection, exactly as Google ships it. Everything around it is the trigger.
Why each piece is there
The fired latch. Five listeners are armed at once and a browser can dispatch several of them in the same frame - a tap produces pointerdown and touchstart together; a scroll gesture produces scroll and mousemove. Without the boolean you would inject gtm.js more than once and push duplicate gtm.start events. The latch is the only thing that makes this safe.
once: true and the explicit removeEventListener. This looks redundant and it is deliberate. once: true only removes the listener for the event that actually fired; the other four are still attached, still calling fire, still doing a function call and a boolean check on every mousemove. The explicit removal loop detaches all of them, so after the tag is away there is nothing hanging off window at all. On a mousemove listener that distinction is not theoretical.
passive: true. For scroll and touchstart in particular, a non-passive listener forces the browser to wait for your handler to return before it knows whether you called preventDefault(), which can stall the compositor and cost you scroll smoothness on exactly the first interaction you are listening for. Declaring the listener passive promises you will not cancel the event and lets scrolling proceed immediately. Chrome defaults some of these to passive at the document level, but saying it explicitly costs nothing and removes the ambiguity.
The 5-second fallback. Without it, a visitor who lands, reads, and closes the tab without moving anything is never counted. setTimeout(fire, 5000) puts a floor under the loss. Once a real interaction fires first, clearTimeout cancels it.
Proving the latch, not assuming it
"Exactly once" is an assertion, so we asserted it. This harness fakes just enough of window and document to run the real snippet in Node, then dispatches four events including a repeat:
var listeners = {}, injected = 0, cleared = 0;
var w = {
addEventListener: function (evt, fn) { (listeners[evt] = listeners[evt] || []).push(fn); },
removeEventListener: function (evt, fn) {
listeners[evt] = (listeners[evt] || []).filter(function (f) { return f !== fn; });
}
};
var firstScript = { parentNode: { insertBefore: function () { injected++; } } };
var d = {
getElementsByTagName: function () { return [firstScript]; },
createElement: function () { return {}; }
};
global.setTimeout = function () { return 1; };
global.clearTimeout = function () { cleared++; };
// ---- the production snippet, pasted unchanged ----
(function (w, d, s, l, i) {
function g() {
w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
var f = d.getElementsByTagName(s)[0], j = d.createElement(s),
dl = l != 'dataLayer' ? '&l=' + l : '';
j.async = true;
j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
}
var fired = false;
function fire() {
if (fired) { return; }
fired = true; g();
evts.forEach(function (evt) { w.removeEventListener(evt, fire); });
clearTimeout(tmr);
}
var evts = ['scroll', 'keydown', 'mousemove', 'touchstart', 'pointerdown'];
evts.forEach(function (evt) { w.addEventListener(evt, fire, { passive: true, once: true }); });
var tmr = setTimeout(fire, 5000);
})(w, d, 'script', 'dataLayer', 'GTM-XXXXXXX');
// --------------------------------------------------
console.log('listeners registered:', Object.keys(listeners).length);
['mousemove', 'scroll', 'pointerdown', 'mousemove'].forEach(function (evt) {
(listeners[evt] || []).slice().forEach(function (fn) { fn(); });
});
console.log('gtm.js injections:', injected);
console.log('dataLayer pushes:', w.dataLayer.length);
console.log('fallback timer cleared:', cleared, 'time(s)');
console.log('listeners still attached:',
Object.keys(listeners).reduce(function (n, k) { return n + listeners[k].length; }, 0));
if (injected !== 1) { throw new Error('FAIL: gtm.js injected ' + injected + ' times'); }
console.log('PASS: g() ran exactly once across 4 events');
Running it with node harness.js, after node --check on the snippet itself:
listeners registered: 5
gtm.js injections: 1
dataLayer pushes: 1
fallback timer cleared: 1 time(s)
listeners still attached: 0
PASS: g() ran exactly once across 4 events
Four dispatched events, one injection, one dataLayer push, zero listeners left behind.
The result
Mobile Lighthouse, same page, same conditions: Total Blocking Time went from 960 ms to 0 ms, and the performance score from 0.78 to 0.99. The vendor scripts still run - the same three payloads, the same roughly 1.4 seconds of main-thread work - but they now run after the measurement window and, more importantly, after the visitor has the page. The work did not disappear. It moved to a moment when nobody is waiting on it.
What this costs you
Be clear-eyed about the trade. A visitor or crawler that never interacts is counted five seconds late, and if the tab is closed before that timer fires, not counted at all. For a site whose analytics inform editorial decisions in aggregate, losing a sliver of non-interacting sessions is a fine price for a whole performance grade. For a site where each pageview has a monetary value attached, it is not.
One thing this is not: a consent mechanism. Whether analytics may run at all is a legal question, decided by your consent banner and your jurisdiction; when it runs is a performance question. If a cookie banner gates analytics on your site, the interaction trigger belongs behind that gate - fire on first interaction and only with consent - not instead of it. Collapsing the two is how sites end up firing tags they were not allowed to fire, with a performance improvement as the cover story. Decide the consent question first, on its own terms, then apply this.
When not to do this
Skip this pattern on e-commerce and anything attribution-critical. If a conversion tag has to fire on page view, or a paid-traffic click must be attributed before a fast bounce, a five-second delay is a real revenue leak and an audit problem with your ad platform. The same goes for A/B testing tools that must run before first paint - you cannot defer those without reintroducing the flicker they exist to avoid.
It is also the wrong tool if the third-party script is doing something the page needs: a chat widget people expect to see, a consent platform, a payment SDK. Delay what is observing the page, not what is part of it.
And if your own bundle genuinely is the problem - if bootup-time puts your application code at the top of that table rather than at 8 ms - then this changes nothing for you and you should go fix the bundle. The point is not that third parties are always to blame. The point is to read the attribution before deciding.
The landing pages we build ship with this pattern in the base template from day one, because retrofitting it means re-auditing every tag. If you have a site scoring badly on Core Web Vitals and no clear picture of where the milliseconds go, that diagnosis is usually a short job, and it is the same instinct we bring to larger web application work. Start a project with your URL and your Lighthouse report and we will tell you what we see, within two business days.
We ship and run our own products. We build yours the same way.
Start a project