Shoora
10/19/2018 - 7:01 AM

Get speed Metrics and send them to Google Analytics

Get speed Metrics and send them to Google Analytics

abGAsendTime = function(){
  this.getLoadTime = function() {
    return performance.timing.loadEventStart - performance.timing.navigationStart;
  }
  this.getTimeToFirstByte = function() {
    var timing = window.performance.timing;
    return timing.responseStart - timing.navigationStart;
  }
  this.getFirstPaintTime = function() {
    if ( ! 'chrome' in window )  return false;
    var load = window.chrome.loadTimes();
    var firstPaintTime = (load.firstPaintTime - load.startLoadTime) * 1000;
    return Math.round(firstPaintTime);
  }
  this.getContentfulPaint = function() {
    //first-contentful-paint
    if ( "getEntriesByType" in performance ) return  Math.round( performance.getEntriesByType('paint')[1].startTime );
    return false;
  }
  this.sendToGA = function(connection) {
    ga( 'send', 'timing', 'abView', 'loadTime', this.getLoadTime() );
    ga( 'send', 'timing', 'abView', 'firstPaintTime', this.getFirstPaintTime() );
    ga( 'send', 'timing', 'abView', 'timeToFirstByte', this.getTimeToFirstByte() );
    ga( 'send', 'timing', 'abView', 'firstContentfulPaint',  this.getContentfulPaint() );
    return true;
  }
  this.track = function() {
    if( 'performance' in window )  this.sendToGA();
  }
  this.init = function(){
    if (typeof ga === 'function') this.track();
    else setTimeout(this.init,500);
  }
}
var myGATime = new abGAsendTime();
myGATime.init();