Skip to content

Instantly share code, notes, and snippets.

@Antoinebr
Created October 20, 2017 15:28
Show Gist options
  • Save Antoinebr/3eb4d9c00afc8b45d15539d318dbcc44 to your computer and use it in GitHub Desktop.
Save Antoinebr/3eb4d9c00afc8b45d15539d318dbcc44 to your computer and use it in GitHub Desktop.
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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment