Home / Blog / How to block scripts before consent without breaking your site

How to block scripts before consent without breaking your site

Mark non-essential scripts as inert with type="text/plain" and data attributes, then let the consent state decide when each one activates. A small loader plus a DOM observer catches scripts injected late by tag managers.

The inert script pattern

The reliable trick is to stop the browser from executing a script before you have decided it may run. Change its type to "text/plain" so the browser ignores it, and store its real type and source in data attributes. Your consent loader then flips eligible scripts back to executable once the visitor grants the matching category. Because the browser never ran the script early, no cookie was set and no request fired.

Handling inline scripts

Inline scripts cannot be swapped by src, so wrap their bodies in a function your loader calls on consent, or move the code into external files the loader controls. Configuration snippets that must exist before consent, like data layer initialization, can stay as long as they set no identifiers and make no network calls.

Catching late injections

Tag managers and chat widgets inject scripts after load, which defeats a one-time scan. A MutationObserver watching for added script tags lets your loader intercept each one, check its category against the current consent state, and either release or hold it. This is also how you handle single-page app route changes, where new scripts appear without a full page load.

Do not break the page

The failure mode to avoid is a site that stays broken when the visitor rejects everything. Test the full reject path: the page must render, navigation must work, and checkout must complete with only strictly necessary scripts running. Blocking everything and hoping for the best is how consent implementations earn their bad reputation.

Get a free consent audit of your website

Free consent audit