David Murdoch
David Murdoch

Reputation: 89302

Async Google Analytics [Javascript Golf]

Unfortunately, this may not be a valid Code-Golf question as it is likely Javascript only; however, since this is likely to be the only useful-in-the-real-world code-golf contest I'm going to go ahead and post it.


The Google Analytics Asyncronous Tracking snippet is used by many websites.

The script goes a little something like this:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Winner will be determined by the shortest RAW DEFLATE (there is a difference between HTTP 1.1 DEFLATE (aka zlib) and RAW DEFLATE) compressed code by byte-count that will load and initialize Async Google Analytics on a page.

In the case of a tie, winner will be determined by raw character count. If it we still have a tie we'll decide by last edit/time submitted.

Some Rules:

Tip:



UDPATE 216/275

Since my original version has been beaten I'll go ahead and post it here:
Note: this has a bug where async gets set to false for all "http" requests

(function(d,t,g){_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]];g=d.createElement(t);g.src=(g.async=location.protocol[5]?"//ssl":"//www")+".google-analytics.com/ga.js";(t=d.getElementsByTagName(t)[0]).parentNode.insertBefore(g,t)})(document,"script")

Upvotes: 18

Views: 5497

Answers (9)

Frank
Frank

Reputation: 2678

This one breaks a few rules, but it's shortest one so far and what I use, 165/196 (16%):

_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]+function(d,e,s){d['get'+e+'sByTagName'](s)[0].appendChild(d['create'+e](s)).src ='//google-analytics.com/ga.js'}(document,'Element','script')

Some notes:

  • It does not set async attribute, but it is ideed asynchronous in modern browsers.
  • It does not rewrite the URL depending on current protocol, but it should work on secure sites as it utilizes protocol-relative URL (I'm by no means an expert, but opening https://google-analytics.com/ga.js in my browser gives me a green lock-icon)
  • I found out that it is not smart to place the script at the end of the document and omit </script></body></html> in order to chew of a few bytes, the script never gets evaluated..
  • I'm sure that if someone is dedicated and wizardly enough, even this can be made shorter ;-)

A more readable formatting:

_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]
+function(d,e,s){
    d['get'+e+'sByTagName'](s)[0]
        .appendChild(d['create'+e](s))
        .src ='//google-analytics.com/ga.js'
}(document,'Element','script')

Upvotes: 0

Matthew Wilcoxson
Matthew Wilcoxson

Reputation: 3622

This might be cheating although technically it obeys all the rules. ;)

<script>var _gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]];</script><script src="//www.google-analytics.com/ga.js" async></script>

Upvotes: 1

gengkev
gengkev

Reputation: 1959

First try, credit for ideas to everybody here.

200/253 (I don't know how to optimize for deflate... the only thing I did was change the variable names)

_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]],function(e,t){(c=e.createElement(t)).async=c.src=(/s:/.test(location)?"//ssl":"//www")+".google-analytics.com/ga.js";(e=e.getElementsByTagName(t)[0]).parentNode.insertBefore(c,e)}(document,"script")

195/258 Would not using (document,"script") help?

_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]],function(){(e=document.createElement("script")).async=e.src=(/s:/.test(location)?"//ssl.":"//")+"google-analytics.com/ga.js";(t=document.getElementsByTagName("script")[0]).parentNode.insertBefore(e,t)}()

For the smallest possible code, you don't even need the "ssl." and "www." prefixes. This still fits within the competition regulations...

175/216

_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]],function(e,t){(a=e.createElement(t)).async=a.src="//google-analytics.com/ga.js";(e=e.getElementsByTagName(t)[0]).parentNode.insertBefore(a,e)}(document,"script")

174/224 And the second and third optimizations combined...

_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]],function(){(e=document.createElement("script")).async=e.src="//google-analytics.com/ga.js";(t=document.getElementsByTagName("script")[0]).parentNode.insertBefore(e,t)}()

Edit: using the regex /s:/ now, and more...

194/266 Apparently reusing _gaq helps...

(_gaq=document.createElement("script")).async=_gaq.src=(/s:/.test(location)?"//ssl":"//www")+".google-analytics.com/ga.js",(_gaq._=document.getElementsByTagName("script")[0]).parentNode.insertBefore(_gaq,_gaq._),_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]]

166/229 and without "ssl" and "www"...

(_gaq=document.createElement("script")).async=_gaq.src="//google-analytics.com/ga.js",(_gaq._=document.getElementsByTagName("script")[0]).parentNode.insertBefore(_gaq,_gaq._),_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]]

Upvotes: 0

unwiredbrain
unwiredbrain

Reputation: 21

183/223 (17.94%) -- async, protocol aware, no namespace pollution

_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]],function(a,b,c,d){a["get"+b+"sByTagName"](c)[0].parentNode.appendChild(d=a["create"+b](c),d.src=d.async="//google-analytics.com/ga.js",d)}(document,"Element","script");

185/228 (18.86%) -- async, protocol aware, no namespace pollution (with the d and e variables)

_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]],function(b,a,c){d=a["create"+b](c),d.async=d.src="//google-analytics.com/ga.js",e=a["get"+b+"sByTagName"](c)[0],e.parentNode.insertBefore(d,e)}("Element",document,"script");

186/233 (20.17%) -- async, protocol aware, no namespace pollution

_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]],(function(a,b,c,d,e){d=a["create"+b](c),d.async=d.src="//google-analytics.com/ga.js",e=a["get"+b+"sByTagName"](c)[0],e.parentNode.insertBefore(d,e)})(document,"Element","script")

Works on Chrome, Firefox, IE 7+, Opera and Safari.

Upvotes: 4

some
some

Reputation: 49582

Updated with versions tested in FF3.6, Opera10, Chrome6, MSIE8:

194/270: with async, with getElementsByTagName cached

(_gaq=document.createElement("script")).src=(/^....s/.test(location)?"//ssl":"//www")+".google-analytics.com/ga.js",(_gaq.a=_gaq.async=document.getElementsByTagName("script")[0]).parentNode.insertBefore(_gaq,_gaq.a),_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]]

192/297: with async, no cache

(_gaq=document.createElement('script')).src=(/^....s/.test(location)?'//ssl':'//www')+'.google-analytics.com/ga.js',_gaq.async=document.getElementsByTagName('script')[0].parentNode.insertBefore(_gaq,document.getElementsByTagName('script')[0]),_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]

189/259: no async, with getElementsByTagName cached

(_gaq=document.createElement('script')).src=(/^....s/.test(location)?'//ssl':'//www')+'.google-analytics.com/ga.js',(_gaq.a=document.getElementsByTagName('script')[0]).parentNode.insertBefore(_gaq,_gaq.a),_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]

188/286: no async, no cache

(_gaq=document.createElement('script')).src=(/^....s/.test(location)?'//ssl':'//www')+'.google-analytics.com/ga.js',document.getElementsByTagName('script')[0].parentNode.insertBefore(_gaq,document.getElementsByTagName('script')[0]),_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]

184/242, no async, appendChild (no cache needed), unknown if it's supported everywhere

(_gaq=document.createElement('script')).src=(/^....s/.test(location)?'//ssl':'//www')+'.google-analytics.com/ga.js',document.getElementsByTagName('script')[0].parentNode.appendChild(_gaq),_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]

Credits:

  • casablanca: /^https/.test(location)
  • matyr: relative path, commas between statements, assignment to async
  • some: no anonymous function and usage of _gaq, non-cacheing of getElementsByTagName, move assignment of async, /^....s/
  • David Murdoch drop type="text/javascript"

Also, changing ' to " may improve compression in your HTML source if you use "" to quote tag attributes.

See comments on this post for more information

Since this post now is community wiki and the accepted answer, I removed my first attempts (you can find them in the revision history if you are interested) and only have the latest revisions visible. See the comments on this post for more information. /some

Upvotes: 7

Tobi
Tobi

Reputation: 2828

(function(d,l,t,g){_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]];(g=d.createElement(t)).src=(l[5]?"ssl.":"")+"google-analytics.com/ga.js";g.async=1;(t=d.getElementsByTagName(t)[0]).parentNode.appendChild(g,t)})(document,location.protocol,"script")

Deflated Length is: 206 bytes. Original length is: 256 bytes. 19.53% savings

vs. no async:

(function(d,l,t,g){_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]];(g=d.createElement(t)).src=(l[5]?"ssl.":"")+"google-analytics.com/ga.js";(t=d.getElementsByTagName(t)[0]).parentNode.appendChild(g,t)})(document,location.protocol,"script")

Deflated Length is: 199 bytes. Original length is: 246 bytes. 19.11% savings

--

a little bit shorter would be this:

var d=document,t="script",g;_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]];(g=d.createElement(t)).src=(location.protocol[5]?"ssl.":"")+"google-analytics.com/ga.js";g.async=1;(t=d.getElementsByTagName(t)[0]).parentNode.appendChild(g,t)

Deflated Length is: 196 bytes. Original length is: 242 bytes. 19.01% savings

vs. no async:

var d=document,t="script",g;_gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]];(g=d.createElement(t)).src=(location.protocol[5]?"ssl.":"")+"google-analytics.com/ga.js";(t=d.getElementsByTagName(t)[0]).parentNode.appendChild(g,t)

Deflated Length is: 188 bytes. Original length is: 232 bytes. 18.88% savings

--

deflated 188 bytes and original 232 bytes is as short as i can go... ;)

Upvotes: 0

Michael F
Michael F

Reputation: 40832

This is probably my best attempt, considering my inexperience with Javascript. Not much going on here:

_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,e){e=d.createElement('script');e.id='s';e.async=1;
e.src='http'+('s'==d.location.protocol[5]?'s://ssl':'://www')+'.google-analytics.com/ga.js';
d=d.getElementByTagName('script');d.parentNode.insertBefore(e,d);})(document);

EDIT

Fixed the bugs @some talked about.

Deflated length: 219 bytes
Original length: 285 bytes

Upvotes: 0

matyr
matyr

Reputation: 5774

(1) first attempt

_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']],function(s,g){g=document.createElement(s),g.async=g.src=(/^https/.test(location)?'//ssl.':'//')+'google-analytics.com/ga.js',s=document.getElementsByTagName(s)[0],s.parentNode.insertBefore(g,s)}('script')

Deflated Length is: 199 bytes. Original length is: 259 bytes. 23.17% savings

(2) (1) + some's 4th

_gaq=document.createElement('script'),_gaq.async=_gaq.src=(/^https/.test(location)?'//ssl.':'//')+'google-analytics.com/ga.js',document.getElementsByTagName('script')[0].parentNode.insertBefore(_gaq,document.getElementsByTagName('script')[0]),_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]

Deflated Length is: 192 bytes. Original length is: 297 bytes. 35.35% savings

Upvotes: 3

casablanca
casablanca

Reputation: 70691

Updated in accordance with updated rules:

Including the <script> tags: Deflated Length is: 226 bytes. Original length is: 298 bytes.

Without the <script> tags: Deflated Length is: 216 bytes. Original length is: 281 bytes.

<script>_gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];(function(d,g){g=d.createElement('script');g.async=true;g.src='http'+(/^https/.test(location)?'s://ssl':'://www')+'.google-analytics.com/ga.js';d=d.getElementsByTagName('script')[0];d.parentNode.insertBefore(g,d);})(document);</script>

Throwing in @some's ideas (only checking location[4] and using 1 for true) saves 4 more bytes (212), but I can't take credit for that.

Upvotes: 2

Related Questions