I'm building a next.js application and would like to load Google Tag Manager (GTM) only AFTER the entire page is loaded. The goal behind this is to improve the website performance.
Has anyone figured out a way how I can run third-party JS code (like GTM) only after the application has fully loaded?
I'm currently adding using the 'conventional' way to inject GTM to my next.js app (source) by adding the <script>
tag into the <Head>
and the <noscript>
tag into the <body>
tag in the _document.js
file:
<Head>
{/* Google Tag Manager */}
<script
dangerouslySetInnerHTML={{
__html: `(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);
})(window,document,'script','dataLayer','GTM-XXXXXXX');`
}}
/>
{/* End Google Tag Manager */}
...
...
</Head>
<body style={{ backgroundColor: theme.palette.primary.background }}>
{/* Google Tag Manager (noscript) */}
<noscript
dangerouslySetInnerHTML={{
__html: '<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe>'
}}
/>
{/* End Google Tag Manager (noscript) */}