Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - What is "var _gaq = _gaq || []; " for?

The Async Tracking code in Google Analytics looks like this:

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); 
})(); 

About The first line:

var _gaq = _gaq || []; 

I think it ensures that if _gaq is already defined we should use it otherwise we should an array.

Can anybody explain what this is for?

Also, does it matter if _gaq gets renamed? In other words, does Google Analytics rely on a global object named _gaq?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This line is there to allow multiple GA snippets in the same page. It ensures that the second snippet doesn't overwrite a _gaq defined by the first.

GA asynchronous tracking works by first defining _gaq as an array. This array acts like a queue, which allows you to push (append) configuration and tracking "commands" (like _trackPageview) onto the end of the queue. Your commands are stored in this array until ga.js fully downloads.

When ga.js is ready, it executes all the commands in the _gaq array and replaces _gaq with an object. This object also has a push method, but instead of queueing up commands, it executes them immediately, because ga.js is available to process them.

This mechanism allows you to make configuration and tracking commands without knowing if the browser has finished downloading ga.js. This is needed because the async snippet downloads ga.js without blocking other code on the page from running. Things would get hairy if that other code (your configuration commands) needed to know the state of ga.js being downloaded.

All of this absolutely does depend on the use of the name _gaq. You shouldn't try to name it if you want asynchronous tracking to work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...