Skip to content

Instantly share code, notes, and snippets.

@mbaersch
Last active October 24, 2025 11:54
Show Gist options
  • Select an option

  • Save mbaersch/35ac8c5063cfb03d8f553fef0e9e910e to your computer and use it in GitHub Desktop.

Select an option

Save mbaersch/35ac8c5063cfb03d8f553fef0e9e910e to your computer and use it in GitHub Desktop.
Custom GTM container code for CookieScript CMP (loads GTM only when targeting or performance consent is granted)

Custom GTM container code for CookieScript CMP

This code loads GTM only when marketing / targeting or performance consent is granted) on a website using CookieScript. This allows to implement both GTM and CookieScript directly on your site and still respect consent.

There are to optional lines of code:

  • you can easily delete the console.log command after making sure that everything works
  • the dataLayer event push is not necessary but serves as a unique trigger that can be used as an alternative to the dataLayer events that CookieScript fires. This is helpful for firing GA and FB Tags at the same event (resulting in matching event ids) when using a server-side GTM and Meta CAPI for example.

Note: CookieScript changed their API at least once and broke existing similar custom implementations already. Be aware that this may happen again in the future.

<script>
function loadconsentedGTM() {
if (window.consentedGTMloaded === true) return;
if (CookieScript && CookieScript.instance) {
let consentedCategories = (CookieScript.instance.currentState()||{}).categories;
if (consentedCategories.indexOf("performance") >= 0 || consentedCategories.indexOf("marketing") >= 0) {
let gtmContainerId = 'GTM-XXXXXXXXXX';
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer',gtmContainerId);
window.consentedGTMloaded = true;
//optional: inform console
console.log('GTM loaded');
//optional: event push for having a unique event for triggering
window.dataLayer=window.dataLayer||[]; window.dataLayer.push({event: 'consent_ready'});
}
}
}
window.addEventListener('CookieScriptLoaded', loadconsentedGTM);
window.addEventListener('CookieScriptAcceptAll', loadconsentedGTM);
window.addEventListener('CookieScriptAccept', loadconsentedGTM);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment