GameAnalytics command queue - GameAnalytics/GA-SDK-JAVASCRIPT GitHub Wiki

The JavaScript GA snippet defines a global ga function known as the "command queue". It's called the command queue because rather than executing the commands it receives immediately, it adds them to a queue that delays execution until the GameAnalytics.js library is fully loaded.

In JavaScript, functions are also objects, which means they can contain properties. The GA snippet defines a q property on the GameAnalytics function object as an empty array. Prior to the GameAnalytics.js library being loaded, calling the ga() function appends the list of arguments passed to the GameAnalytics() function to the end of the q array.

For example, if you were to run the GA snippet and then immediately log the contents of GameAnalytics.q to the console, you'd see an array, two items in length, containing the two sets of arguments already passed to the GameAnalytics() function:

console.log(GameAnalytics.q);

// Outputs the following:
// [
//   ['setEnabledInfoLog', true],
//   ['initialize', 'GAME_KEY', 'SECRET_KEY']
// ]

Once the GameAnalytics.js library is loaded, it inspects the contents of the GameAnalytics.q array and executes each command in order. After that, the GameAnalytics() function is redefined, so all subsequent calls execute immediately.

This pattern allows developers to use the GameAnalytics() command queue without having to worry about whether or not the analytics.js library has finished loading. It provides a simple, synchronous-looking interface that abstracts away most of the complexities of asynchronous code.

Adding commands to the queue

All calls to the GameAnalytics() command queue share a common signature. The first parameter, the "command", is a string that identifies a particular GameAnalytics.js method. Any additional parameters are the arguments that get passed to that method.

The rest of the documentation will refer to how to call methods unsing the traditional way and using the GameAnalytics() command queue.

 

NEXT  →