How-to

So blockieren Sie Drittanbieter-Skripte bis zur Einwilligung

Technische Anleitung zu Skript-Blockierungsmethoden: Änderung des Skripttyps, Verwendung von Datenattributen und automatische Blockierung — mit Codebeispielen.

Veröffentlicht am

So blockieren Sie Drittanbieter-Skripte bis zur Einwilligung

Showing a cookie banner is the easy part. Actually stopping third-party scripts from firing before consent — and making them fire after — is the part that breaks most home-grown implementations. If your banner says “please accept” but the Meta Pixel has already loaded and set its cookies, you're not compliant. You're just visually present.

This guide covers the three methods CMPs use to actually block scripts, when each one applies, and the edge cases that catch people out.

Three methods

There are basically three ways to intercept a third-party script before it executes:

  1. Script type swap. Mark the script as type="text/plain" so the browser doesn't execute it. Swap to type="text/javascript" after consent.
  2. MutationObserver intercept. Watch the DOM for any <script> being inserted, hold it back if it doesn't pass a consent check.
  3. Service Worker fetch interception. Intercept network requests at the Service Worker layer, block requests to non-consented domains.

Most CMPs (ours included) default to Method 1 for known scripts and use Method 2 as a fallback for scripts that get injected dynamically. Method 3 is rare in commercial CMPs because of operational complexity, but it's the strongest guarantee if you can deploy a Service Worker.

Method 1: Script type swap

The browser only executes scripts whose type attribute is empty, text/javascript, or module. Set it to anything else and the script sits inert in the DOM. This is the trick.

Take a Google Analytics tag that would normally look like:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX"></script>

Rewrite as:

<script
  type="text/plain"
  data-ct-category="statistics"
  src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX"
></script>

Now the browser sees a script with an unknown type and skips execution. The data-ct-category attribute (or whatever your CMP uses) tells the consent runtime which category controls this script.

After the visitor accepts the matching category, the CMP finds all scripts with that category attribute and swaps their type:

document.querySelectorAll('script[data-ct-category="statistics"]')
  .forEach(s => {
    const replacement = document.createElement('script');
    for (const attr of s.attributes) {
      if (attr.name === 'type') continue;
      replacement.setAttribute(attr.name, attr.value);
    }
    replacement.type = 'text/javascript';
    s.parentNode.replaceChild(replacement, s);
  });

You can't just change the type attribute on the existing element — the browser only evaluates a script when it's first inserted into the DOM. You have to clone the script tag with the new type and insert that, which triggers the load.

Pros: simple, fast, works with HTTP caching, no runtime overhead.

Cons: requires you (or your CMS) to modify the script tags in your HTML. Doesn't catch scripts injected by other scripts.

Method 2: MutationObserver intercept

If you can't modify the script tags directly — for example, scripts injected by Google Tag Manager, by another third-party widget, or by user-generated content — you need to watch the DOM and intercept new script insertions.

Pattern looks like:

const observer = new MutationObserver(mutations => {
  for (const m of mutations) {
    for (const node of m.addedNodes) {
      if (node.tagName !== 'SCRIPT') continue;
      const src = node.src;
      if (isBlockedDomain(src) && !hasConsent(categoryFor(src))) {
        node.type = 'text/plain';
        node.removeAttribute('src');
        pendingScripts.push({ src, category: categoryFor(src) });
      }
    }
  }
});
observer.observe(document.documentElement, {
  childList: true,
  subtree: true,
});

The trick is to intercept the script before the browser starts loading it. MutationObserver fires synchronously after the script is inserted but before the browser processes it. If you change the type to text/plain and remove the src attribute, the script won't execute.

After consent, you replay the held scripts by creating new ones with the original src and proper type.

Pros: catches dynamically injected scripts, no HTML modification needed.

Cons: has to maintain a list of blocked domains, slight runtime overhead, can miss scripts inserted before the observer is attached. Order matters: the observer has to be set up before any third-party scripts have a chance to load.

Method 3: Service Worker fetch interception

For the strongest guarantee, intercept at the network layer. Register a Service Worker that watches all fetch requests from the page and blocks those going to non-consented third-party domains.

self.addEventListener('fetch', event => {
  const url = new URL(event.request.url);
  if (isThirdPartyTracker(url.hostname) && !hasConsentFor(url.hostname)) {
    event.respondWith(new Response('', { status: 204 }));
  }
});

Pros: catches everything, even scripts that get past Methods 1 and 2. Works for image pixels, beacons, anything the page tries to load.

Cons: requires a Service Worker to be registered (which has its own first-visit caveat — Service Workers don't apply to the page that registers them), doesn't catch in-process script execution, and adds operational complexity (Service Worker debugging, update-on-deploy gotchas). Most teams don't need this.

Edge cases that catch people out

Scripts inside iframes. A third-party iframe (a YouTube embed, a Facebook widget) runs in its own context. Your script-blocking runtime doesn't see what loads inside it. The fix is to block the iframe itself until consent, or use the same type="text/plain" trick on <iframe> tags (set data-src instead of src, swap on consent).

Dynamic imports. import() at runtime fetches via the same network layer that scripts use. Method 3 (Service Worker) catches these. Methods 1 and 2 do not.

Shadow DOM. Scripts inside web components with Shadow DOM are visible to MutationObserver if you observe the document and the components don't use mode: closed. Otherwise you need to attach observers to each shadow root.

Preconnect / DNS-prefetch hints. Even when the script is blocked, browser hint tags like <link rel="preconnect" href="..."> will still establish connections to tracking domains. That leaks information (your IP, your User-Agent) to the third party even without a cookie. Remove the hint tags too, or gate them behind consent.

Scripts loaded by other scripts. A script you legitimately load (your own code) that then loads a tracking script will bypass Method 1 entirely. MutationObserver catches it; Service Worker catches it. Method 1 alone doesn't.

What I'd read next

For the legal context that drives all of this, GDPR Cookie Consent and the ePrivacy Directive. For the Google-specific signal protocol, Google Consent Mode v2. For the SPA-specific implementation considerations, Cookie Consent for SPAs.