vkashti / utils / gtm.js
gtm.js
Raw

/**
 * Helper script to load the Google Tag Manager script with proper compression
 * Include this script in your Next.js app to load GTM with compression support
 */
export function loadGTM(id = 'G-XXXXXXXX') {
  // Create a script element to load our compressed GTM script
  const script = document.createElement('script');
  
  // Try to use the local compressed version first
  const supportsCompression = 'HTMLScriptElement' in window;
  
  // If the browser supports modern features, use our compressed local version
  if (supportsCompression) {
    script.src = '/scripts/gtm.min.js';
  } else {
    // Fallback to the original Google Tag Manager script
    script.src = `https://www.googletagmanager.com/gtag/js?id=${id}`;
  }
  
  script.async = true;
  document.head.appendChild(script);
  
  // Initialize GTM
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', id);
}