Skip to content

Instantly share code, notes, and snippets.

@heikkivihersalo
Last active June 24, 2024 16:35
Show Gist options
  • Save heikkivihersalo/364a2ee362578874c078a25a627cbada to your computer and use it in GitHub Desktop.
Save heikkivihersalo/364a2ee362578874c078a25a627cbada to your computer and use it in GitHub Desktop.
Delayed Tag Manager Script
/**
* Based on Mattias Fjellvang script -
* https://constantsolutions.dk/2020/06/delay-loading-of-google-analytics-google-tag-manager-script-for-better-pagespeed-score-and-initial-load/
*
*/
var TAGMANAGER_HOST = 'www.googletagmanager.com';
var TAGMANAGER_CONTAINER_ID = 'GTM-XXXXXX';
var TAGMANAGER_TIMEOUT = 2000;
var initGTMOnEvent=function(t){initGTM(),t.currentTarget.removeEventListener(t.type,initGTMOnEvent)},initGTM=function(){if(window.gtmDidInit)return!1;window.gtmDidInit=!0;var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.onload=function(){dataLayer.push({event:"gtm.js","gtm.start":new Date().getTime(),"gtm.uniqueEventId":0})},t.src=`https://${TAGMANAGER_HOST}/gtm.js?id=${TAGMANAGER_CONTAINER_ID}`,document.head.appendChild(t)};document.addEventListener("DOMContentLoaded",function(){setTimeout(initGTM,TAGMANAGER_TIMEOUT)}),document.addEventListener("scroll",initGTMOnEvent),document.addEventListener("mousemove",initGTMOnEvent),document.addEventListener("touchstart",initGTMOnEvent);
<?php
/**
* Add scripts to site <head> -tag
* @return void
*/
function ksd_add_to_wp_head(): void {
?>
<script>
var TAGMANAGER_HOST = 'www.googletagmanager.com';
var TAGMANAGER_CONTAINER_ID = 'GTM-XXXXXXX';
var TAGMANAGER_TIMEOUT = 2000;
var initGTMOnEvent=function(t){initGTM(),t.currentTarget.removeEventListener(t.type,initGTMOnEvent)},initGTM=function(){if(window.gtmDidInit)return!1;window.gtmDidInit=!0;var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.onload=function(){dataLayer.push({event:"gtm.js","gtm.start":(new Date).getTime(),"gtm.uniqueEventId":0})},t.src=`https://${TAGMANAGER_HOST}/gtm.js?id=${TAGMANAGER_CONTAINER_ID}`,document.head.appendChild(t)};document.addEventListener("DOMContentLoaded",(function(){setTimeout(initGTM,TAGMANAGER_TIMEOUT)})),document.addEventListener("scroll",initGTMOnEvent),document.addEventListener("mousemove",initGTMOnEvent),document.addEventListener("touchstart",initGTMOnEvent);
</script>
<?php
}
add_action('wp_head', 'ksd_add_to_wp_head', 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment