Created
March 11, 2016 13:11
-
-
Save acdha/a1fd7e91f8cd5c1f6916 to your computer and use it in GitHub Desktop.
Record first paint time from chrome.loadTimes (Chrome/Opera, IE11) to Google Analytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
'use strict'; | |
function recordTimeToFirstPaint() { | |
// Use Chrome's loadTimes or IE 9+'s msFirstPaint to record the time to render in milliseconds: | |
var firstPaintTime, timingSource; | |
if ('chrome' in window && $.isFunction(window.chrome.loadTimes)) { | |
var loadTimes = window.chrome.loadTimes(); | |
// A small percentage of traffic from Chrome in the wild returns impossibly large values – 2+ | |
// days! – which need to be filtered out: | |
firstPaintTime = loadTimes.firstPaintTime - loadTimes.startLoadTime; | |
if (firstPaintTime > 3600) { | |
Raven.captureMessage('chrome.loadTimes() reported impossible values', | |
{extra: {loadTimes: loadTimes}}); | |
return; | |
} | |
// Convert from seconds to milliseconds: | |
firstPaintTime = Math.round(firstPaintTime * 1000); | |
timingSource = 'chrome.loadTimes'; | |
} else if ('performance' in window) { | |
var navTiming = window.performance.timing; | |
if (navTiming.navigationStart === 0) { | |
return; // IE9 bug - see below | |
} | |
// See http://msdn.microsoft.com/ff974719 | |
firstPaintTime = navTiming.msFirstPaint - navTiming.navigationStart; | |
timingSource = 'msFirstPaint'; | |
} | |
if (typeof firstPaintTime == 'number' && firstPaintTime > 0) { | |
ga('send', { | |
hitType: 'timing', | |
transport: 'beacon', | |
timingCategory: 'RUM', | |
timingVar: 'First Paint (ms)', | |
timingValue: firstPaintTime, | |
timingLabel: timingSource | |
}); | |
} | |
} | |
// Defer collecting data until after the load event has finished to avoid an IE9 | |
// bug where navigationStart will be 0 until after the browser updates the | |
// performance.timing data structure: | |
$(window).on('load', function () { | |
setTimeout(recordTimeToFirstPaint); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment