简体   繁体   中英

How long does ga() take to complete?

In my ajax call of log in page, if it returns a param named is_first_login = 1, then I need to call ga() to send GA event.

And immediately after that, the page is redirected to main dashboard page. But not sure why, ga() is not fired sometimes.

How long does GA event firing takes to complete in average?

  // Make ajax call for login.
  fn._post('user.post_login', {
    username: username,
    pwd: pwd,
    redirect_to: redirect_to,
  }, function (json) {

    if ( !json.error && json.is_first_login ) {

      if (typeof ga !== 'undefined') {
        var event_category = 'Subscribe - First Login',
            event_action = 'First Login',
            event_label = 'Partner';

        ga('send', 'event', event_category, event_action, event_label);
        ga('newTracker.send', 'event', event_category, event_action, event_label);
      }
    }

    if (json.redirect) {
      fn._redirect(json.redirect);
      return;
    }

    $('.msg').remove();
    if (json.error) {
      fn._inlineMsg(jUsername.parent(), json.msg);
      jUsername.focus();
      jLoginBtn.parent().removeClass('loading');
    }
  });

You can never tell how long the tracking request is going to take on the client's computer. My tracking requests take usually arround 25ms (rarely it took much more - like 960ms).

You can test it yourself. Just run following from your browsers console:

var start = (new Date()).getTime();
ga('send', 'event', 'event_category', 'event_action', 'event_label', {
    hitCallback: function() {
      console.log("Tracking took " + ((new Date()).getTime() - start));
    }
});

However, the time you get is just informative and you can't rely on it. On some other client's computer may get different response times.

Therefore you might want to put your redirection code inside a callback function.

setTimeout(function(){
  //redirect here
}, 2000);

ga('send', 'event', event_category, event_action, event_label, {
  hitCallback: function() {
    //redirect here
  }
});

The setTimeout is used just in case, the hitCallback never happens (which is also possible).

Read more on https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits#knowing_when_the_hit_has_been_sent

Do not forget to call event.preventDefault() when binding tracking code onto element that does redirect by default (eg <a>, <button> ...)

ga() queues the analytics request, mainly to wait for the full analytics library to download. ( https://developers.google.com/analytics/devguides/collection/analyticsjs/command-queue-reference )

If you are redirecting before that resource loads, then the call out to google analytics will not be made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM