Skip to content

Instantly share code, notes, and snippets.

@SamSaffron
Last active November 8, 2022 05:06
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 SamSaffron/64eb2f004280489739e3b68a9e934900 to your computer and use it in GitHub Desktop.
Save SamSaffron/64eb2f004280489739e3b68a9e934900 to your computer and use it in GitHub Desktop.
function getStats() {
var domainStats = {};
let resourcesOnPage = {};
document.querySelectorAll("SCRIPT, LINK").forEach((r) => {
let src = r.src;
if (r.rel === "preload" || r.rel === "stylesheet") {
src = r.href;
}
if (src) {
if (src[0] === "//") {
src = window.location.protocol + "//" + window.location.hostname + src;
}
resourcesOnPage[src] = true;
}
});
performance.getEntriesByType("resource").forEach((r) => {
if (!resourcesOnPage[r.name]) {
return;
}
resourcesOnPage[r.name] = "found";
let duration = r.responseEnd ? r.responseEnd - r.startTime : -1;
let url = new URL(r.name);
let stats = domainStats[url.host]
if (!stats) {
stats = {count: 1, min: duration, max: duration, total: duration, latest: r.responseEnd, failed: duration == -1 ? 1 : 0};
} else {
stats.count += 1;
if (r.responseEnd > stats.responseEnd) {
stats.responseEnd = r.responseEnd;
}
if (duration == -1) {
stats.failed += 1;
} else {
if (duration < stats.min || stats.min === -1) { stats.min = duration };
if (duration > stats.max) { stats.max = duration };
}
stats.total += duration;
}
domainStats[url.host] = stats;
});
var failed = [];
Object.keys(resourcesOnPage).forEach((k) => {
if (resourcesOnPage[k] !== "found") {
failed.push(resourcesOnPage[k]);
}
});
if (failed.length) {
domain["failed"] = failed;
}
return domainStats;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment