Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify JavaScript like Google Analytics?

Most of you are probably familiar with this little tracking code offered by Google Analytics.

<script>
(
    function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    }
)(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-00000000-0', 'auto');
ga('send', 'pageview');
</script>

The interesting part is that this little excerpt contains arguments that form the word isogram. This script also uses arguments to declare variables to shave off some bits from the final file size. Arguably, you would not use this pattern when writing the code (?), so my question is, how does Google minify its code and are these techniques available to mere mortals, too?

I found online this example by Stephen Morley that includes a code that looks like something you'd write before minifying it. I took that code and run it through Google's very own Closure Compiler on advanced optimisation. As expected, the resulting code is nothing like the actual script used by Google Analytics.

(function(){window.b="ga";"ga"in window||(window.a=function(){window.a.q.push(arguments)},window.a.q=[]);window.a.c=(new Date).getTime();var c=document.createElement("script");c.src="//www.google-analytics.com/analytics.js";c.async=!0;var d=document.getElementsByTagName("script")[0];d.parentNode.insertBefore(c,d)})();

This time, the code is less DRY and bigger, even without the two extra commands.

So to clarify, I am curious how the Google engineers arrived to the above result (I do not think their code actually looks like the one in Stephen's example), and could this process be replicated even if you are not a part of Google? Thank you in advance!

like image 919
lmenus Avatar asked Jun 24 '16 13:06

lmenus


People also ask

How do you minify in JavaScript?

To minify JavaScript, try UglifyJS. The Closure Compiler is also very effective. You can create a build process that uses these tools to minify and rename the development files and save them to a production directory.

Should you minify JavaScript?

It is important to minify your CSS and minimise JavaScript files so they can load faster on your web pages. There are many reasons why you should minify your CSS and JavaScript: Reduce file size: The more code there is in a file, the larger it will be. Minified code is usually much smaller than the original version.

How does Minify JavaScript work?

How Minification Works. Minification works by analyzing and rewriting the text-based parts of a website to reduce its overall file size. Minification extends to scripts, style sheets, and other components that the web browser uses to render the site. Minification is performed on the web server before a response is sent ...

What is Minifier JavaScript?

Minification, also known as minimization, is the process of removing all unnecessary characters from JavaScript source code without altering its functionality. This includes the removal of whitespace, comments, and semicolons, along with the use of shorter variable names and functions.


1 Answers

Google is nice, because they give us a full documentation about many thing on https://developers.google.com

So many of your responses can be found on :

  • Google analytics file

  • Closure Compiler documentation

  • Closure Compiler repository

Here is the unminified Analytics.js

(function(i, s, o, g, r, a, m){
  i['GoogleAnalyticsObject'] = r; // Acts as a pointer to support renaming.

  // Creates an initial ga() function.
  // The queued commands will be executed once analytics.js loads.
  i[r] = i[r] || function() {
    (i[r].q = i[r].q || []).push(arguments)
  },

  // Sets the time (as an integer) this tag was executed.
  // Used for timing hits.
  i[r].l = 1 * new Date();

  // Insert the script tag asynchronously.
  // Inserts above current tag to prevent blocking in addition to using the
  // async attribute.
  a = s.createElement(o),
  m = s.getElementsByTagName(o)[0];
  a.async = 1;
  a.src = g;
  m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

// Creates a default tracker with automatic cookie domain configuration.
ga('create', 'UA-XXXXX-Y', 'auto');

// Sends a pageview hit from the tracker just created.
ga('send', 'pageview');

And here is the minified version they provide (pretty version):

(function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date();
    a = s.createElement(o),
        m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

And here the minified version with closure compiler tools

(function (a, e, f, g, b, c, d) {
    a.GoogleAnalyticsObject = b;
    a[b] = a[b] || function () {(a[b].q = a[b].q || []).push(arguments)};
    a[b].l = 1 * new Date;
    c = e.createElement(f);
    d = e.getElementsByTagName(f)[0];
    c.async = 1;
    c.src = g;
    d.parentNode.insertBefore(c, d)
})(window, document, "script", "//www.google-analytics.com/analytics.js", "ga");
ga("create", "UA-XXXXX-Y", "auto");
ga("send", "pageview");

It's look like the same.
You can find more details on the project on Github repository.

like image 153
callmemath Avatar answered Oct 26 '22 23:10

callmemath