Cookies & tracking
How to block cookies and scripts until consent
A banner that asks for consent doesn't stop anything by itself. To block cookies before consent, you have to stop the scripts, iframes and pixels that set them from loading until the visitor allows their category.
- Plain English
- Written for website owners
- Free to read
On this page
- Why a banner alone doesn't block anything
- Technique 1: Neutralize script tags with type="text/plain"
- Technique 2: Iframes, images and pixels with data-src
- Technique 3: Load scripts from your own code after consent
- Technique 4: Tag manager consent settings
- Technique 5: Decide on the server
- Withdrawal and cookies already set
- Common leaks
- Test your blocking
- Frequently asked questions
To block cookies until consent, you have to stop the code that sets them from running. Non-essential scripts, iframes and pixels must stay inactive until the visitor allows their category, and then load. The most common techniques are: changing script tags to type="text/plain" so the browser ignores them, moving iframe and image URLs into data-src, loading scripts from your own code only after consent, using your tag manager's consent settings, and rendering tags on the server only for visitors who've agreed. Most sites combine two or three of them.
This is called prior blocking, and it's what EU and UK rules require. Article 5(3) of the ePrivacy Directive and PECR regulation 6 call for consent before anything non-essential is stored or read.
Why a banner alone doesn't block anything
Browsers run scripts as they find them in the page. If your analytics snippet is in the <head>, it runs as soon as the page loads, sets its cookies and sends its first request, often before the banner has even appeared. Recording "rejected" a second later changes nothing for that page view.
Deleting the cookies afterwards isn't a fix either. The data has already been sent, and the rule is about storing or accessing information in the first place. So the goal is simple: nothing in the analytics, functional or marketing categories may execute or make a request until consent. To decide what belongs where, see cookie categories explained.
Technique 1: Neutralize script tags with type="text/plain"
Browsers execute a <script> only if its type is a JavaScript type. If you set type="text/plain", the browser treats the contents as inert text and doesn't download an external src either. A consent script can later create a real copy of the tag, which then runs normally.
<!-- Before: runs immediately -->
<script async src="https://analytics.example.com/tag.js"></script>
<!-- After: inert until the analytics category is allowed -->
<script type="text/plain" data-category="analytics" async
src="https://analytics.example.com/tag.js"></script>
If you're building this yourself, the release step looks like this:
function releaseCategory(category) {
var selector = 'script[type="text/plain"][data-category="' + category + '"]';
document.querySelectorAll(selector).forEach(function (blocked) {
var script = document.createElement('script');
for (var i = 0; i < blocked.attributes.length; i++) {
var attr = blocked.attributes[i];
if (attr.name !== 'type') script.setAttribute(attr.name, attr.value);
}
if (blocked.src) {
// Dynamically inserted scripts are async by default; keep order unless async was set
script.async = blocked.hasAttribute('async');
} else {
script.text = blocked.text;
}
blocked.parentNode.replaceChild(script, blocked);
});
}
// Call after the visitor chooses, and on page load if a choice is already stored
releaseCategory('analytics');
Watch the order of execution. An inline script runs the instant it's inserted, so it won't wait for an external library released just before it. Snippets that queue calls, like Google's gtag() or Meta's fbq(), handle this. Code that calls a library immediately may not.
This is how PrivacyQuick blocks scripts: you add type="text/plain" and data-category, and the SDK releases the tag once the visitor allows that category, copying all other attributes across. The script blocking docs have examples for GA4, Meta Pixel and Hotjar.
Technique 2: Iframes, images and pixels with data-src
Iframes and images start loading as soon as they have a src. Move the URL into data-src and copy it back after consent:
<iframe data-src="https://www.youtube-nocookie.com/embed/VIDEO_ID"
data-category="marketing" width="560" height="315"
title="Product demo video" allowfullscreen></iframe>
<img data-src="https://pixel.example-ads.com/p.gif?id=123"
data-category="marketing" width="1" height="1" alt="">
document.querySelectorAll('[data-src][data-category="marketing"]').forEach(function (el) {
el.src = el.getAttribute('data-src');
el.removeAttribute('data-src');
});
An empty iframe confuses visitors, so add a placeholder: a short note, a thumbnail you host yourself, and a button that opens your cookie settings or loads just that embed. This click-to-load pattern works well for video and maps. See YouTube embeds and cookies for details.
Also remove <noscript> tracking pixels from ad snippets. They fire only when JavaScript is off, which is exactly when your banner can't ask for consent.
Technique 3: Load scripts from your own code after consent
If you build your front end in JavaScript, for example in a single-page app, you may prefer not to put tags in the HTML at all. Load them from code once consent exists:
var analyticsLoaded = false;
function loadAnalytics() {
if (analyticsLoaded) return;
analyticsLoaded = true;
var s = document.createElement('script');
s.src = 'https://analytics.example.com/tag.js';
s.async = true;
document.head.appendChild(s);
}
// consent.has() and consent.onChange() stand in for your consent tool's API
if (consent.has('analytics')) loadAnalytics();
consent.onChange(function () {
if (consent.has('analytics')) loadAnalytics();
});
With PrivacyQuick, the equivalents are PrivacyQuick.has('analytics') and PrivacyQuick.on('change', fn), or the pq:consent DOM event. See the JavaScript API. The same pattern works for npm packages: import them dynamically with import() inside the consent check, rather than at the top of your bundle.
Technique 4: Tag manager consent settings
If your tags live in Google Tag Manager, block them there rather than in the page:
- Set a denied default first. Before any tag fires, set Consent Mode defaults to denied, using a consent tool's GTM integration or a tag on the Consent Initialization – All Pages trigger.
- Use built-in consent checks. Google's own tags (GA4, Google Ads, Floodlight) read the consent state automatically.
- Add consent checks to other tags. For Meta, LinkedIn, Hotjar and Custom HTML tags, open the tag's Consent Settings, choose Require additional consent for tag to fire, and add
ad_storageoranalytics_storageas appropriate. - Update on choice. When the visitor chooses, send an update. Tags that were waiting fire then.
The default and update calls look like this, whether written by hand or sent by your consent tool:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied',
analytics_storage: 'denied',
wait_for_update: 500
});
</script>
<!-- later, after the visitor allows analytics -->
<script>
gtag('consent', 'update', { analytics_storage: 'granted' });
</script>
The default must run before the GTM container snippet. PrivacyQuick sends both calls for you, with analytics mapped to analytics_storage and marketing mapped to the three ad signals, so GTM works without a CMP template. The full GTM walk-through is in setting up consent in Google Tag Manager.
Consent Mode isn't always blocking
Google Consent Mode has two approaches. In the basic setup, Google tags don't load until consent, which is true blocking. In the advanced setup, tags load with consent denied and send cookieless pings, which Google uses for modeling. No cookies are set, but data is still sent to Google before consent, and some regulators and lawyers are cautious about that. Read Consent Mode basic vs advanced before choosing.
Technique 5: Decide on the server
If your pages are rendered on the server, you can leave non-essential tags out of the HTML entirely unless the consent cookie allows them. Here's an Express example, assuming the cookie-parser middleware and a consent cookie your banner writes:
app.get('/', function (req, res) {
var allowed = (req.cookies.site_consent || '').split(','); // e.g. "analytics,marketing"
res.set('Cache-Control', 'private, no-store');
res.render('home', { loadAnalytics: allowed.indexOf('analytics') >= 0 });
});
{% if loadAnalytics %}
<script async src="https://analytics.example.com/tag.js"></script>
{% endif %}
Two caveats apply. First, the page the visitor consents on was rendered before the choice, so you still need a client-side release, or a reload, for that page. Second, caching: a CDN that stores one visitor's version of the page and serves it to everyone breaks this completely. Mark these responses private, or keep the decision client-side.
Server-side tagging, where tags send data to your own tagging server, which forwards it to vendors, is a different thing. It moves where the data goes, but it doesn't remove the need for consent. Your server still has to respect the consent state before forwarding anything.
Withdrawal and cookies already set
Blocking also has to work in reverse. When a visitor withdraws consent:
- Scripts that already ran on the current page can't be stopped, so reload the page after withdrawal, with those tags blocked. PrivacyQuick does this automatically.
- Third-party cookies already set will expire on their own schedule, and no longer get refreshed. You can delete your own first-party analytics cookies, such as
_ga, from a consent-change listener. - Future page views must keep the tags blocked.
Common leaks
- Hard-coded snippets in theme templates that bypass your tag manager or blocking setup.
- Plugins and apps that inject their own tracking scripts at runtime. Elements added by JavaScript after the page loads aren't seen by tag-based blocking.
- Custom HTML tags in GTM without additional consent checks.
- Inline code that calls a blocked library, for example
fbq('track', 'Purchase')on a thank-you page. Guard it withif (window.fbq). - Embeds and fonts loaded from third-party servers, which send the visitor's IP address before any choice.
- Categories missing from the banner. A script tagged
marketingnever loads if the banner offers no Marketing switch.
Test your blocking
- Open a clean browser profile, with DevTools open on the Network panel and Preserve log on.
- Load the page from an opt-in region and don't touch the banner. You should see no requests to analytics or ad hosts, and only strictly necessary cookies in the Application panel.
- Click Reject all and browse a few pages. Still nothing.
- Start clean, click Accept all, and confirm each tag now loads.
- Withdraw a category and check that its tags stop.
Our guide to checking cookies in Chrome DevTools shows where to look at each step. To check every page rather than a handful, run a free PrivacyQuick scan. It reports which cookies and third-party hosts appear before anyone has consented.
Frequently asked questions
Does a cookie banner block cookies automatically?
Not necessarily. Many banners only record the visitor's choice. Unless your scripts are tied to that choice, through tagging, a tag manager or code that checks consent, they still load and set cookies as before.
Can I delete cookies after they're set instead of blocking them?
No, that doesn't meet the rule. In the EU and UK, consent is needed before information is stored on or read from the device. Deleting a cookie afterwards doesn't undo the fact that it was set and the data was sent.
Is Google Consent Mode enough to block cookies?
With the basic setup, Google tags don't load until consent, so cookies are blocked. With the advanced setup, tags load and send cookieless pings while consent is denied, which some regulators view more cautiously. Consent Mode only controls Google tags and tags you configure to respect it.
How do I know if blocking works?
Test from a clean browser profile in an opt-in region. Before you click the banner, the Network panel should show no analytics or ad requests and the Application panel should show only strictly necessary cookies.
Check your own website in 30 seconds
Our free scanner lists every cookie and tracker your site sets, sorted into categories, before you add a banner.
This guide is general information, not legal advice. Laws and regulator guidance change; check the current rules for your situation or ask a lawyer.