I develop an web application with preact. The total size of the webapp is about 30KB gzipped (Google Analytics is about 14KB). I want to add google analytics but I dont want that google analytics slows down the initial page load. The recommended method to include analytics.js () is
<!-- Google Analytics -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q|| .
[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'> .
</script>
<!-- End Google Analytics -->
This works fine, but the analytics.js gets downloaded before my other stuff gets downloaded. Im pretty sure that this affects the page load as you can see in this picture)
What is the recommend way to download analytics after the page finished loading. (In my case after 'menu' gets downloaded)
I know this is old, but you could add the defer
attribute instead of the async
attribute to your tag. Async will download the file asynchronously, but it still blocks the main thread while it's running the javascript. Defer will also download asynchronously, but will wait to run the javascript until the HTML parses. This is one of many articles that explains the difference between async and defer
If you really don't want the GA affecting load speeds, you could add an event listener that waits for the window 'load' event before injecting the GA script tags. That is probably overkill for a 30KB web app, but GA will have almost no affect on your page loads.
GA shouldn't be slowing down your website right now
Your script is async
, which means it's not blocking the browser from carrying on with other tasks. Accordingly, from the trace screenshot you gave, we can indeed see that while analytics.js
is being requested, the browser is making other concurrent requests (bundle.js
, ,menu
), so you're good.
Loading GA after page load
If you still want to defer loading of GA after page load for best practices, just call GA later:
Window Loaded
trigger which fires when the browser is done loading the page: https://productforums.google.com/forum/#!topic/tag-manager/xOMFkfH0U4k;context-place=forum/tag-manager
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With