Skip to content

Instantly share code, notes, and snippets.

@montmanu
Last active May 24, 2017 22:19
Show Gist options
  • Save montmanu/99b0c0bcd4ee2c99ee78526461d3738e to your computer and use it in GitHub Desktop.
Save montmanu/99b0c0bcd4ee2c99ee78526461d3738e to your computer and use it in GitHub Desktop.
Get array of unique, 3rd party resources
var firstPartyHostnamePattern = /^(?:.*)(?:nytimes\.com|nyt\.com|nyt\.net)$/;
// filter out 1st party resources
var thirdPartyResources = window.performance.getEntriesByType('resource').filter(function (entry){
var url = new URL(entry.name);
return !firstPartyHostnamePattern.test(url.hostname);
});
// reduce to unique host names
var thirdPartyHostnames = thirdPartyResources.map(function (entry){
return new URL(entry.name).hostname;
}).reduce(function (prev, curr){
if (prev.indexOf(curr) === -1) { prev.push(curr); }
return prev;
}, []);
// generate map from host name to array of resources
var thirdPartyUrlsByHostname = thirdPartyHostnames.reduce(function (prev, curr){
var resourcesByHost = {};
resourcesByHost[curr] = thirdPartyResources.filter(function (resource){
var resourceHostname = new URL(resource.name).hostname;
return resourceHostname === curr;
}).map(function (resource){
return new URL(resource.name).pathname;
});
return Object.assign(prev, resourcesByHost);
}, {});
// calculate total 3p resources
var total3pResources = Object.keys(thirdPartyUrlsByHostname).reduce(function (prev, curr){
return prev + thirdPartyUrlsByHostname[curr].length;
}, 0);
// calculate % of all resources that are 3p resources
var thirdPartyPercent = (total3pResources / window.performance.getEntriesByType('resource').length) * 100;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment