Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load google analytics after page load

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)

enter image description here

What is the recommend way to download analytics after the page finished loading. (In my case after 'menu' gets downloaded)

like image 370
Simon Ludwig Avatar asked Apr 16 '18 14:04

Simon Ludwig


2 Answers

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.

like image 156
JakeAve Avatar answered Oct 30 '22 16:10

JakeAve


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:

  • Using Javascript: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
  • Using a Tag Manager: for instance with Google Tag Manager, use the 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
like image 45
Max Avatar answered Oct 30 '22 17:10

Max