I know tracking codes for piwik, google analytic and other similar stuff, placed at the end of page to not affect page rendering. But there is a minor problem that the page still not complete. The progress indicator in user browser still cycling! If you test your page (which contain tracking code) with tools like WebPageTest you see the overall time is count the tracking code requests (at least 2 request one for JS and another for tracking).
I make a simple delay by using window.setTimeout(trackingfunction, 3000)
. The tracking code will fired three seconds after the line executed! Guessing the page is completely done at that time. It lead to indicator stop just after page load and don't cycle again when calling tracking code. In the tools also the tracking code not shown and the reported time is page real time.
Does it correct tracking? Does it track javascript-enabled bots?
PS:
I read this article, he also do somthing to defer the loading of thirdparty javascripts. but i cant decide does his work is correct or not?
There are pros and cons to deferring the loading of the Google Analytics JS file until after the load
event fires. Ultimately, what you decide to do is based on the needs of your individual site. There's not a one-size-fits-all answer here.
load
event for your page will happen quicker. This will (as you mentioned) mean the spinner is not spinning for as long, and performance analysis tools will report your page as loading faster.ga()
function, you run the risk of those calls generating errors. If you're going to delay the downloading of the analytics.js
script, at minimum, you should run the ga()
initialization code in the <head>
since it's very small and its performance affect will be negligible.<head>
is to make sure it's loaded as quickly as possible and avoid the problem of errors preventing it from being loaded.Bottom line: Yes, it's OK, but only do it if you know what you're doing, you understand the implications, and you're aware of the downsides and don't care about them.
Ilya Grigorik wrote a good article about how <script async>
address some of your concerns about this. You should also note that Google Analytics has a recommended snippet that uses <script async>
as well.