Skip to content

Instantly share code, notes, and snippets.

@Zolmeister
Created August 11, 2017 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zolmeister/90219132d0f0030408d067e738d723ad to your computer and use it in GitHub Desktop.
Save Zolmeister/90219132d0f0030408d067e738d723ad to your computer and use it in GitHub Desktop.
// send network request timings to Google Analytics
(function() {
var nativeOpen = XMLHttpRequest.prototype.open
var nativeSend = XMLHttpRequest.prototype.send
var startTime = null
var pendingCount = 0
XMLHttpRequest.prototype.open = function(_, url) {
this._url = url
return nativeOpen.apply(this, arguments)
}
XMLHttpRequest.prototype.send = function() {
if (this._url.indexOf('https://www.google-analytics.com') === -1) {
if (startTime == null) startTime = Date.now()
pendingCount += 1
this.addEventListener('loadend', function() {
pendingCount -= 1
if (this.responseURL.indexOf('https://www.google-analytics.com') !== -1) return
// group multiple network requests together,
// including those which are serially dependent
setTimeout(function() {
if (pendingCount == 0) {
var elapsed = Date.now() - startTime
var path = window.location.pathname + window.location.search
startTime = null
ga('send', 'timing', 'Network Chunk', 'load', elapsed, path)
}
})
})
}
return nativeSend.apply(this, arguments)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment