Skip to content

Instantly share code, notes, and snippets.

@sabrysuleiman
Created November 23, 2023 17:27
Show Gist options
  • Save sabrysuleiman/325c445b265800b02e0d561a28ca12a1 to your computer and use it in GitHub Desktop.
Save sabrysuleiman/325c445b265800b02e0d561a28ca12a1 to your computer and use it in GitHub Desktop.
Lazy Load GTM
<script>
function loadScript(url) {
let isLoaded = document.querySelectorAll('.search-script');
if(isLoaded.length > 0) { return; }
let myScript = document.createElement("script");
myScript.src = url;
myScript.async = 'async';
myScript.className = 'search-script';
document.head.appendChild(myScript);
}
window.addEventListener('scroll', function() {
var timer;
clearTimeout(timer);
timer = setTimeout(function() { loadScript('https://www.googletagmanager.com/gtm.js?id=YOUR-ID'); }, 1000);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment