shinsenter / defer.js

🥇 A lightweight JavaScript library that helps you lazy load (almost) anything. Defer.js is dependency-free, highly efficient, and optimized for Web Vitals.
https://shinsenter.github.io/defer.js/
MIT License
277 stars 45 forks source link

Defer Google Analytics 4 gtag js script #107

Closed nafatrue closed 2 years ago

nafatrue commented 2 years ago

hi i'm trying to defer gtag Google Analytics 4 js script but no success here is my code Defer.js('https://www.googletagmanager.com/gtag/js?id=XXXXX','gtag-js', 10); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'XXXXX');

shinsenter commented 2 years ago

@nafatrue Since GA script will be lazyloaded, so the gtag outside Defer scope may not work until the script fully downloaded.

You may try:

<script>
Defer.js(['https://www.googletagmanager.com/gtag/js?id=XXXXX', 'gtag-js', 100, function() {
        window.dataLayer = window.dataLayer || []; 
        function gtag(){dataLayer.push(arguments);} 
        gtag('js', new Date()); 
        gtag('config', 'XXXXX');
    });
</script>
shinsenter commented 2 years ago

@nafatrue BTW, did you get any error?