Consenti
Tutorial — Frontend Only — Step 5 of 6

Gate a Script

Load a third-party script only once consent is granted.

Consenti ships several ways to gate third-party code on consent. Pick whichever fits what you're gating — a script tag, an SDK call, or a whole category at once. Each snippet is independent.

ConsentScript — inject/remove a <script> tag, keyed to one cookie

ts
import { ConsentScript } from '@consenti/ui'

new ConsentScript({
  cookieId: 'analytics',
  widget,
  src: 'https://cdn.example.com/analytics.js',
  onLoad: () => console.log('Analytics loaded'),
  onRevoke: () => console.log('Analytics removed'),
})

CategoryScript — same, but keyed to a whole category

Fires only when every cookie in the category is granted — good for a bundle of ad tags that should load or unload together.

ts
import { CategoryScript } from '@consenti/ui'

new CategoryScript({
  categoryId: 'marketing',
  widget,
  src: 'https://example.com/ad-pixel.js',
})

ConsentAction — run a callback instead of loading a script

Use this for SDKs that expose their own opt-in/opt-out method (Segment, Mixpanel, Sentry, …) rather than a script tag to toggle.

ts
import { ConsentAction } from '@consenti/ui'

new ConsentAction({
  id: 'analytics',
  widget,
  onGrant: () => analyticsSdk.optIn(),
  onDeny: () => analyticsSdk.optOut(),
})

CategoryAction — callback keyed to a whole category

ts
import { CategoryAction } from '@consenti/ui'

new CategoryAction({
  id: 'marketing',
  widget,
  onGrant: () => adSdk.enableAll(),
  onDeny: () => adSdk.disableAll(),
})

scanConsentScripts — declarative, zero-JS gating via data attributes

Mark an inert <script type="text/plain"> tag instead of writing any of the above in JS:

html
<script type="text/plain" data-consenti-category-script="marketing" src="https://example.com/pixel.js"></script>

<script type="text/plain" data-consenti-consent-script="analytics">
  /* inline snippet, injected verbatim when granted */
</script>
ts
import { scanConsentScripts } from '@consenti/ui'

// Runs automatically once per init — safe to call again after adding tags dynamically
scanConsentScripts(widget)

BannerTrigger — bonus: let visitors reopen the banner/modal

ts
import { BannerTrigger } from '@consenti/ui'

new BannerTrigger({ widget, el: '#footer-cookie-settings', action: 'modal' })

Full reference, including every payload shape, in the Events reference.