Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 1 * new Date() instead of new Date().getTime() in GA snippet?

I am inserting GA snippet in my TypeScript code and seeing this:

i[r].l = 1 * new Date();

TypeScript compiler complains that new Date() must be number or any, but not Date.

I turned this into this:

i[r]['l'] = new Date().getTime();

Which leads to the same result.

If the priority is to reduce the size, then I find this even more compact giving the same result:

i[r]['l'] = +new Date();

I have no idea why that smart-ass variant with implicit casting is used.

Is there anything hidden I don't understand or is it just guys want to look smarter? Is it to make it shorter in length?

like image 685
Sergei Basharov Avatar asked Nov 02 '16 10:11

Sergei Basharov


1 Answers

Is there anything hidden I don't understand...

Nope, it's absolutely, 100% just to make it shorter in length.

In fact, if you look at the newest recommend snippet, it uses just +new Date, which is two bytes shorter than your +new Date() version:

<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>

It's true that a lot of linters and code build tools will complain about these types of practices, and for good reason. You probably shouldn't be using clever tricks like this in your source code because they're harder to read, not always clear on their intent, confusing, etc.

However, almost every minifier out there does use them to produce the most efficient code, and there's absolutely nothing technically wrong with them.

The point is you should write readable code and then depend on a minifier/compiler to make it as small and efficient as possible.

Google Analytics, however, cannot just assume that everyone who consumes their snippet will run it through a minifier, so it gives developers the snippet pre-minified.


The most common way to deal with including pre-minified code in your source files and avoid linter/compiler warnings is to ignore the entire block, a feature almost every linter offers.

For example, with ESLint, you can do this (something I see in a lot of people's source code around their Google Analytics snippet) by placing a comment directly before and after the block to ignore:

/*eslint-disable */
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
/*eslint-enable */
like image 170
Philip Walton Avatar answered Sep 29 '22 20:09

Philip Walton