A Cookie Banner Rendered by JavaScript Is a Core Web Vitals Problem
A consent banner built by script after load arrives late, shifts the page, and can become the LCP element. Moving the markup into the server response fixed CLS and LCP on one of our products.
Almost every consent banner we meet is built the same way: a script loads, waits for the DOM, and injects a full-width fixed bar into the page. It is the obvious design and it is measurably bad for Core Web Vitals, because the largest new element on the screen arrives after the browser has already decided what the page looks like.
The symptom: two metrics, one cause
On one of our products, LearnCoachAssist, the mobile Lighthouse performance score was 0.57 with a CLS of 0.475. That CLS number is roughly five times the "needs improvement" threshold. The page itself was not complicated. The banner was.
A script-injected banner hurts in two separate ways, and it helps to keep them apart.
Layout shift. The browser paints the page. Then the consent script runs, creates a bar, and inserts it. If the bar is in normal flow - or if it is fixed but the page compensates for it by adding padding to body - everything moves. That movement, multiplied by the fraction of viewport affected, is your CLS. A full-width bar at the bottom of a phone viewport is a large fraction.
Largest Contentful Paint. This one surprises people. LCP is the render time of the largest image or text block in the viewport. On a text-first page with no hero image - a pricing page, a documentation page, a sign-up form - a full-width consent banner with a paragraph of text in it can genuinely be the largest contentful element. If it is, your LCP is not "when the page appeared", it is "when the third-party script finished", which is typically hundreds of milliseconds later and entirely outside your control. Even when the banner is not the LCP element itself, the script fetch and its main-thread work compete with the resources that are.
Diagnosis
Do not guess which of the two you have. Lighthouse names the LCP element explicitly in the "Largest Contentful Paint element" audit, and lists the biggest individual shifts under "Avoid large layout shifts" with the offending node for each. If the banner's container shows up in either, you have your answer.
The runtime version is a five-line check you can paste into the console on the live page:
new PerformanceObserver(function (list) {
var entries = list.getEntries();
var last = entries[entries.length - 1];
console.log('LCP', Math.round(last.startTime), 'ms', last.element);
}).observe({ type: 'largest-contentful-paint', buffered: true });
new PerformanceObserver(function (list) {
list.getEntries().forEach(function (entry) {
if (entry.hadRecentInput) { return; }
console.log('shift', entry.value.toFixed(4),
entry.sources.map(function (s) { return s.node; }));
});
}).observe({ type: 'layout-shift', buffered: true });
If the node logged next to your largest shift is the banner, stop reading Lighthouse and start moving markup.
The fix, in four parts
The principle we apply on every landing page build is simple: the banner is part of the page, so the page's first byte should contain it. Everything below follows from that.
1. Render the markup server-side
Put the banner in a partial and include it from the base template, so it is in the initial HTML response with everything else.
<!-- templates/partials/cookie_banner.html -->
<div id="cookie-banner" class="cookie-banner" role="dialog" aria-live="polite"
aria-label="Cookie consent">
<p class="cookie-banner__text">
I use cookies for analytics. You can accept all, or only the ones this
site needs to work.
</p>
<div class="cookie-banner__actions">
<button type="button" class="cookie-banner__btn"
data-consent-action="necessary">Necessary only</button>
<button type="button" class="cookie-banner__btn cookie-banner__btn--primary"
data-consent-action="all">Accept all</button>
</div>
</div>
And in base.html, just before </body>:
{% include "partials/cookie_banner.html" %}
A PHP or Blade stack is the same idea with different syntax - @include('partials.cookie-banner'), or a plain include in the layout. Nothing here is Django-specific except the tag.
2. Inline the banner's CSS in the head
This part matters more than it looks. If the banner's styles come from an additional stylesheet request, you have swapped a late script for a late - or render-blocking - style, and the banner either flashes unstyled or delays first paint. Its CSS is a few hundred bytes; put it in a <style> block in <head> along with the rest of your critical CSS.
<style>
.cookie-banner {
position: fixed;
left: 0; right: 0; bottom: 0;
z-index: 60;
display: flex;
flex-wrap: wrap;
gap: .75rem;
align-items: center;
justify-content: space-between;
padding: 1rem 1.25rem;
background: #10151c;
color: #e9eef5;
font-size: .9375rem;
line-height: 1.45;
}
/* Returning visitor: decided before first paint, never rendered. */
html[data-consent="set"] .cookie-banner { display: none; }
</style>
position: fixed is doing real work here: a fixed element is out of normal flow, so it cannot push content and cannot contribute a layout shift to anything around it. Resist the urge to add compensating padding-bottom to body from JavaScript - that reintroduces exactly the shift you removed. If the banner must not cover content, reserve the space in the server-rendered CSS as well, conditioned on the same attribute.
3. Hide it before first paint when consent already exists
Server-rendering the banner creates a new problem: a returning visitor who already consented would now see the banner in the first paint and watch it disappear. That flash is worse than the original bug.
The fix is a tiny synchronous script in <head>, before any stylesheet, that reads the consent cookie and marks the root element. Synchronous and in the head is the point - it runs before the browser paints, so the CSS rule above suppresses the banner and it is never seen.
(function (d) {
var name = 'consent_v2';
var parts = d.cookie.split(';');
for (var i = 0; i < parts.length; i++) {
var p = parts[i], eq = p.indexOf('=');
if (eq !== -1 && p.slice(0, eq).trim() === name && p.slice(eq + 1).trim() !== '') {
d.documentElement.setAttribute('data-consent', 'set');
return;
}
}
})(document);
Note what that is not: it is not document.cookie.indexOf('consent_v2='). The naive substring check matches any cookie whose name ends with your name - old_consent_v2, _ga_consent_v2 - and hands you the wrong value. It also fails to URL-decode, so a value containing = or ; comes back percent-encoded. We ran both against a set of awkward jars:
function readCookie(name, jar) {
var parts = (jar || '').split(';');
for (var i = 0; i < parts.length; i++) {
var p = parts[i], eq = p.indexOf('=');
if (eq === -1) { continue; }
if (p.slice(0, eq).trim() !== name) { continue; }
return decodeURIComponent(p.slice(eq + 1).trim());
}
return null;
}
function naive(name, jar) {
var i = jar.indexOf(name + '=');
return i === -1 ? null : jar.slice(i + name.length + 1).split(';')[0];
}
[
'a=1; consent_v2=all; b=2',
'consent_v2=stats%3Dyes%3Bads%3Dno',
'a=1; b=2',
'old_consent_v2=none; a=1',
'consent_v2=',
''
].forEach(function (jar) {
console.log(JSON.stringify(jar).padEnd(38),
'correct=' + JSON.stringify(readCookie('consent_v2', jar)).padEnd(22),
'naive=' + JSON.stringify(naive('consent_v2', jar)));
});
Which prints:
"a=1; consent_v2=all; b=2" correct="all" naive="all"
"consent_v2=stats%3Dyes%3Bads%3Dno" correct="stats=yes;ads=no" naive="stats%3Dyes%3Bads%3Dno"
"a=1; b=2" correct=null naive=null
"old_consent_v2=none; a=1" correct=null naive="none"
"consent_v2=" correct="" naive=""
"" correct=null naive=null
Row four is the bug. A visitor with a stale old_consent_v2 cookie and no current consent gets treated as having decided. That is a compliance problem dressed up as a one-liner.
If your framework can read the cookie server-side, do that too and skip the head script entirely - in Django, a context processor is enough:
CONSENT_COOKIE = 'consent_v2'
def cookie_consent(request):
"""Context processor: what the banner partial needs, decided server-side."""
value = request.COOKIES.get(CONSENT_COOKIE, '')
return {
'consent_value': value,
'consent_given': value != '',
'consent_cookie_name': CONSENT_COOKIE,
}
Then wrap the include in {% if not consent_given %} and the banner is not even in the response. The head script becomes the fallback for pages served from a cache that ignores the cookie - which, if you have a CDN in front, is most of them. Keep both; they agree.
4. The JavaScript now only wires up buttons
With the markup already in the document, the consent script stops being a DOM builder and becomes an event handler. It can be deferred, because nothing visual depends on it.
(function () {
var COOKIE = 'consent_v2';
var banner = document.getElementById('cookie-banner');
if (!banner) { return; }
function save(value) {
var year = 60 * 60 * 24 * 365;
document.cookie = COOKIE + '=' + encodeURIComponent(value) +
'; path=/; max-age=' + year + '; SameSite=Lax';
document.documentElement.setAttribute('data-consent', 'set');
if (value === 'all') {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ event: 'consent_granted' });
}
}
banner.addEventListener('click', function (event) {
var button = event.target.closest('[data-consent-action]');
if (!button) { return; }
save(button.getAttribute('data-consent-action'));
});
})();
One delegated listener on the container, so adding a third button later is a template change only.
The result, and the pitfall that will bite you
On LearnCoachAssist, that pass - server-rendering the banner, plus splitting a large inline script out of the critical path - took mobile Lighthouse performance from 0.57 to 0.84, CLS from 0.475 to 0.041 and LCP from 2.7 s to 2.0 s. Two changes shipped together, so we will not pretend to a precise split between them; the CLS collapse is attributable to the banner and the layout work, and the LCP improvement to both.
The single biggest failure mode when you move banner markup out of JavaScript and into a template is drift. The consent script looks for specific ids, classes and data attributes. Copy them byte-identically - including class names you think are decorative - or the script silently finds nothing, the buttons do nothing, and consent is never recorded. That failure is invisible in Lighthouse and invisible in a quick click-through if you already have the cookie. Test it in a fresh private window, every time.
Two smaller pitfalls. If your CDN caches HTML, the server-rendered banner is cached with it, so the head script must stay as the client-side correction - and the consent cookie must not be part of the cache key unless you want two copies of every page. And role="dialog" on a bar that does not trap focus is a lie to screen readers; either implement the focus trap or use a plain landmark with aria-live, which is what a non-blocking bar actually is.
When not to do this
If your consent vendor's script is contractually the source of truth for the banner - the case with most enterprise CMPs, where the banner text, the vendor list and the regional logic are audited artefacts of their platform - then reproducing their markup in your template puts you on the hook for keeping it in sync with their legal updates. Do not take that on to save 0.1 of CLS. Ask the vendor for their server-side or pre-rendered integration instead; the better ones have one.
The same applies when banner content varies by region. If you need a different banner for EEA, UK, California and everyone else, server-rendering means either shipping every variant or resolving geography before the response goes out. If your stack can do that at the edge, fine. If it cannot, a script that fetches the right variant is the honest design, and you should spend your CLS budget somewhere else.
And if the banner is genuinely small and anchored to the bottom of a page whose real LCP element is a hero image at the top, measure before you refactor. You may find the banner contributes almost nothing, in which case this is work you do not need to do.
Consent banners are a common cause of a bad CLS score on otherwise well-built sites, and they are usually a small fix. If you want that done properly on a landing page or as part of a wider web application build, we do this work. Start a project with the URL and the Lighthouse report and we will tell you where the milliseconds are going, within two business days.
We ship and run our own products. We build yours the same way.
Start a project