Dawid Adach
Dawid Adach

Reputation: 769

Asynchronous JS call with parameters like GA

I am trying create client side JS code which will call external JS server side script with some parameters, I was looking at Google Analitycs sample as this is exactly what I would like to achieve, however I don't really get how does it work...

(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','//www.google-analytics.com/analytics.js','ga');

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

I wonder how the server side script is parsing these elements.. I tried to reverse engineer http://www.google-analytics.com/analytics.js code but I don't get it..

Can I find somewhere simple snippet using same method which shows client - server asynchronous communication ?

Upvotes: 0

Views: 241

Answers (1)

Eike Pierstorff
Eike Pierstorff

Reputation: 32760

This script does not communicate with the server at all. This just loads the analytics.js library, which is the file that actually does the tracking.

The simplest way to transfer data across domain boundaries is to dynamically create an image tag, point it to a server side script that does the processing (and returns a transparent 1x1 image) and append the tracking parameters. You need to keep track of an id that you use to recognize recurring visitors and stitch pageview into session, so you need a few functions that can read, write and update cookies. That's among the thing the analytics.js file does.

There are other ways to send data - for example Google Analytics uses the sendBeacon-method if available. That has the advantage that it does not wait for a server response (so it won't be canceled if the browser unloads the document). However that is not always available, and in those cases the image request is used as a fallback.

So the simplest way to send data to a server is to create an image url and create an image dynamically.

img = new Image(); 
img.src ="http://myserver.com?param1=foo&param2=bar";

You do not even need to add that to the DOM, the image will be send regardless.

Upvotes: 1

Related Questions