Created
August 19, 2015 18:33
-
-
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
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'; | |
/* 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