Skip to content

Instantly share code, notes, and snippets.

@benaadams
Last active August 29, 2015 14:19
Show Gist options
  • Save benaadams/f7d1e9136d8c60939467 to your computer and use it in GitHub Desktop.
Save benaadams/f7d1e9136d8c60939467 to your computer and use it in GitHub Desktop.
Jquery SPA insights
// needs these polyfills included: https://gist.github.com/benaadams/bdd53bc4c65a3cee0ae8
// is doing console.log rather than calling application insights
function ClearResourceTimings() {
try{
if (window.performance) {
if (performance.clearResourceTimings) {
performance.clearResourceTimings();
} else if (performance.webkitClearResourceTimings) {
performance.webkitClearResourceTimings();
}
}
} catch (e) { }
}
function RecordTimings(url, type) {
if (url.startsWith('/')) { // only machine local urls
var title = document.title
if (url.startsWith('/api/')) { // For Web Api use url as title
title = url.substring(5);
if (title.indexOf('?') > 0) {
title = type + ' ' + title.substring(0, title.indexOf('?'));
}
}
var longUrl = location.href.substring(0, location.href.indexOf('/', 8)) + url;
if (window.performance && window.performance.getEntriesByName) {
var perf = performance.getEntriesByName(longUrl);
if (perf.length > 0) {
perf = perf[0];
var duration = perf.duration;
var networkMs = perf.connectEnd - perf.startTime;
var sendMs = perf.responseStart - perf.requestStart;
var receiveMs = perf.responseEnd - perf.responseStart;
var startDom = performance.now();
setImmediate(function () {
var domProcessingMs = performance.now() - startDom;
duration += domProcessingMs;
console.log(title, url, duration, networkMs, sendMs, receiveMs, domProcessingMs);
// var timings = new Microsoft.ApplicationInsights.Telemetry.Timings(duration, networkMs, sendMs, receiveMs, domProcessingMs);
// appInsights.trackPageView(title, url, undefined, undefined, timings);
});
} else {
// exact url match not found
console.log(title, ur);
// var timings = new Microsoft.ApplicationInsights.Telemetry.Timings(duration, networkMs, sendMs, receiveMs, domProcessingMs);
// appInsights.trackPageView(title, url, undefined, undefined, timings);
}
ClearResourceTimings();
} else {
console.log(title, url);
// appInsights.trackPageView(title, url);
}
}
}
$(document).ajaxComplete(function (event, xhr, settings) {
var url = settings.url;
try {
RecordTimings(url, settings.type);
} catch (e) {}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment