Skip to content

Instantly share code, notes, and snippets.

@acdha
Created August 19, 2015 18:33
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save acdha/365f7bc0e10d2e7b7865 to your computer and use it in GitHub Desktop.
Save acdha/365f7bc0e10d2e7b7865 to your computer and use it in GitHub Desktop.
Record time to first paint on Chrome/IE using Google Analytics user timing
(function ($) {
'use strict';
/* Based on https://github.com/wikimedia/mediawiki-extensions-NavigationTiming/ */
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();
firstPaintTime = Math.round((loadTimes.firstPaintTime - loadTimes.startLoadTime) * 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