"Control Freak" pristup za vanilla JS SPA sa prilagođenim ruterom - modularan setup koji juniori mogu da debaguju bez straha.
Standardni GTM setapi ne funkcionišu na Single Page Applications sa prilagođenim ruterima. History Change okidač se aktivira pre nego što DOM završi ažuriranje. Nativni GTM Consent Mode je crna kutija u SPA okruženjima. Rezultat: dupli eventi, nedostajući page_view-ovi i signali pristanka koji stižu prekasno.
Umesto jednog ogromnog nečitljivog skripta, ova prezentacija pokazuje modularan sistem - 6 tagova, 3 okidača, svaki sa tačno jednim zadatkom.
GTM ne "vidi" nativne pozive gtag('consent', 'update') u realnom vremenu unutar SPA. Bridge presreće te pozive i konvertuje ih u prilagođeni GTM event.
var origPush = window.dataLayer.push.bind(window.dataLayer);
window.dataLayer.push = function() {
for (var i = 0; i < arguments.length; i++) {
var item = arguments[i];
if (item && typeof item === 'object' &&
item[0] === 'consent' && item[1] === 'update') {
var consentData = item[2] || {};
origPush({
'event': 'gtm_consent_update',
'consent_analytics': consentData.analytics_storage || 'denied',
'consent_ads': consentData.ad_storage || 'denied'
});
}
}
return origPush.apply(this, arguments);
};gtm_consent_update. Bez ovoga, GTM ne bi znao da se pristanak promenio u realnom vremenu unutar SPA.Standardni "History Change" okidač se aktivira pre nego što prilagođeni ruter završi ažuriranje DOM-a.
var lastPath = location.pathname;
function checkAndPush() {
var currentPath = location.pathname;
if (currentPath !== lastPath) {
lastPath = currentPath;
window.dataLayer.push({
event: 'spa_navigation',
page_location: location.href,
page_path: currentPath,
page_title: document.title,
spa_timestamp: new Date().toISOString()
});
}
}
// MutationObserver sa debounce od 150ms
var observer = new MutationObserver(function() {
clearTimeout(window._ferticoSpaTimeout);
window._ferticoSpaTimeout = setTimeout(checkAndPush, 150);
});
observer.observe(document.documentElement, {
childList: true, subtree: true
});page_location i page_title uvek 100% tačni.if (window._ferticoGA4Loaded) return;
window._ferticoGA4Loaded = true;
var s = document.createElement('script');
s.async = true;
s.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
document.head.appendChild(s);
window.gtag('js', new Date());
window.gtag('config', 'G-XXXXXXXXXX', {
'send_page_view': false,
'transport_type': 'beacon'
});spa_navigation okidač. Nema više automatskih page_view eventa koje GTM generiše, a mi ne kontrolišemo.spa_navigation event.