Skip to content

Commit

Permalink
Add Google Analytics tag. Ensure proper load order and error handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
codecodeio committed May 14, 2024
1 parent bcfbe35 commit aad4b68
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions best-cigars-guide/scripts/delayed.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,43 @@ import { sampleRUM } from './aem.js';
sampleRUM('cwv');

// add more delayed functionality here

function onError(tagName) {
/* eslint no-console: ["error", { allow: ["error"] }] */
console.error(`The ${tagName} script failed to load.`);
}

function onGALoad() {
/* global dataLayer */
window.dataLayer = window.dataLayer || [];
function gtag() {
// eslint-disable-next-line prefer-rest-params
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'GT-M6QM788');
gtag('set', 'linker', { domains: ['www.famous-smoke.com'] });
}

function loadGoogleAnalytics() {
// Load the Google Analytics library
const tag = document.createElement('script');
tag.async = true;
tag.src = 'https://www.googletagmanager.com/gtag/js?id=GT-M6QM788';
document.head.appendChild(tag);
// Configuration script
tag.onload = onGALoad;
tag.onerror = onError('Google Analytics');
}

// Check if Google Analytics is loaded
function isGALoaded() {
return window.dataLayer && Array.isArray(window.dataLayer);
}

// Load Scripts
if (window.location.hostname !== 'localhost') {
if (!isGALoaded()) {
loadGoogleAnalytics();
}
}

0 comments on commit aad4b68

Please sign in to comment.