Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do websites like Hotjar and Google Analytics use complex tracking code instead of just a <script> tag?

Website that use JS tracking usually use this kind of code :

<script>
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:9999,hjsv:5};
        a=o.getElementsByTagName('head')[0];
        r=o.createElement('script');r.async=1;
        r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
        a.appendChild(r);
    })(window,document,'//static.hotjar.com/c/hotjar-','.js?sv=');
</script>

In the end, those scripts just add a <script> tag to the <head> of the page, so surely there must be a reason why they're doing it this way.

Is it for ad-blocking bypass reasons ? Wouldn't the generated request be the same as if it was hardcoded in the <head> ?

like image 286
Olivier Delaunay Avatar asked Dec 10 '22 10:12

Olivier Delaunay


1 Answers

I'm the chief architect at Hotjar so I'll explain the reasons why we did it in this particular way.

  1. We need to do things before the main script is loaded.

    h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};

That particular line allows us to store actions to execute once the main script is loaded. It allows for things like hj('trackVirtualPageView', '/url') to be called before our script is loaded.

  1. We can store things like settings as part of the snippet.

    h._hjSettings={hjid:9999,hjsv:5};

That could absolutely be added as part of the query string when loading the script. The downside of using that approach is that we would get less optimal caching since it would be impossible for a browser to know that script.js?hjid=1 and script.js?hjid=2 actually loads the same JS file.

  1. What we're doing in the last part is actually just creating a <script async=1> tag and adding it to the <head> which works really well. The reason we're doing it through JS is that we like to make it as easy as possible for our users by only asking them to put code in one place.

There might be an even better to do what we're doing which I'm blissfully unaware of, and in case there is, please reach out and tell me about it! :)

like image 165
Erik Näslund Avatar answered Feb 09 '23 00:02

Erik Näslund