大多数人可能都熟悉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>
Run Code Online (Sandbox Code Playgroud)
有趣的是,这个小摘录包含形成单词isogram的参数.此脚本还使用参数声明变量以从最终文件大小中删除一些位.可以说,在编写代码(?)时你不会使用这种模式,所以我的问题是,谷歌如何缩小其代码并且这些技术是否也适用于凡人?
我在网上找到了Stephen Morley的这个例子,其中包含一个看起来像你在缩小它之前写的东西的代码.我接受了这些代码并通过Google自己的Closure Compiler进行高级优化.正如预期的那样,生成的代码与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)})();
Run Code Online (Sandbox Code Playgroud)
这次,即使没有两个额外的命令,代码也更少DRY和更大.
因此,为了澄清,我很好奇Google工程师是如何得出上述结果的(我不认为他们的代码实际上看起来像斯蒂芬的例子中的那个),即使你不是谷歌的一部分,这个过程是否可以复制?先感谢您!
javascript google-analytics minify google-closure-compiler bundling-and-minification