Dynamic Google Tag Manager Load on Cookie Consent | 404 Error

29 Views Asked by At

I'm trying to dynamically load Google Tag Manager (GTM) based on user consent in a JavaScript function. My GTM ID is correct and the container is published (and updated).

I'm getting a 404 Not Found error when the script attempts to load.

This is the function I've written to load it:


function loadGTM() {
  if (window.dataLayer && window.dataLayer.find(obj => obj['gtm.start'])) {
    console.log('GTM already loaded');
    return;
  }
  
  (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);
    
    console.log('GTM URL:', j.src);
  })(window, document, 'script', 'dataLayer', 'GTM-XXXXXXX');
}

The console logs the GTM URL being requested i.e https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXXX

The browser's Network tab shows a 404 error for the GTM script request.

Any suggestions on what might be causing this issue and how to resolve it would be greatly appreciated. This is the first time I've dynamically loaded GTM on my site before.

Please let me know if you need any more information to help find the issue.

Kind regards

0

There are 0 best solutions below