Skip to content

Instantly share code, notes, and snippets.

@umaar
Created August 2, 2024 13:45
Show Gist options
  • Save umaar/9c25e9161d3a03c33e5714e921841718 to your computer and use it in GitHub Desktop.
Save umaar/9c25e9161d3a03c33e5714e921841718 to your computer and use it in GitHub Desktop.
const API_URL = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed";
function setUpQuery(url) {
const params = new URLSearchParams({
url: url,
});
return `${API_URL}?${params}`;
}
async function fetchPageSpeedData(url) {
const queryUrl = setUpQuery(url);
console.log(`Fetching data for URL: ${url}`);
console.log(`Full query URL: ${queryUrl}`);
try {
const response = await fetch(queryUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// console.log("Raw API response:", JSON.stringify(data, null, 2));
return data;
} catch (error) {
console.error(`Error fetching data for ${url}:`, error);
return null;
}
}
function extractMetrics(data) {
if (!data || !data.id || !data.lighthouseResult) {
console.error("Invalid data structure received from API");
return null;
}
const lighthouse = data.lighthouseResult;
const loadingExperience = data.loadingExperience;
return {
url: data.id,
cls: lighthouse.audits["cumulative-layout-shift"]?.numericValue,
inp: loadingExperience?.metrics?.INTERACTION_TO_NEXT_PAINT?.category,
lcp: lighthouse.audits["largest-contentful-paint"]?.numericValue,
performanceScore: lighthouse.categories?.performance?.score,
};
}
function compareMetrics(metrics, metricName) {
const validMetrics = metrics.filter(
m => m && m[metricName] !== undefined && m[metricName] !== null
);
if (validMetrics.length === 0) {
console.log(`\nNo valid data for ${metricName}`);
return;
}
console.log(`\n${metricName.toUpperCase()} Comparison:`);
validMetrics.forEach(m => console.log(`${m.url}: ${m[metricName]}`));
if (metricName === "inp") {
compareINP(validMetrics);
} else {
compareNumericMetrics(validMetrics, metricName);
}
}
function compareINP(metrics) {
const categoryOrder = ["FAST", "AVERAGE", "SLOW", "NONE"];
const sorted = metrics.sort(
(a, b) => categoryOrder.indexOf(a.inp) - categoryOrder.indexOf(b.inp)
);
const best = sorted[0];
const worst = sorted[sorted.length - 1];
if (best.inp === worst.inp) {
console.log(`All websites have the same INP category: ${best.inp}`);
} else {
console.log(`Best performing: ${best.url} (${best.inp})`);
console.log(`Worst performing: ${worst.url} (${worst.inp})`);
}
}
function compareNumericMetrics(metrics, metricName) {
const sorted = metrics.sort((a, b) => a[metricName] - b[metricName]);
const best = sorted[0];
const worst = sorted[sorted.length - 1];
if (best[metricName] === worst[metricName]) {
console.log(
`All websites have the same ${metricName} value: ${best[
metricName
].toFixed(2)}`
);
} else if (worst[metricName] === 0) {
console.log(
`Cannot calculate improvement percentage as the worst value is 0.`
);
console.log(
`Best performing: ${best.url} (${best[metricName].toFixed(2)})`
);
console.log(
`Worst performing: ${worst.url} (${worst[metricName].toFixed(2)})`
);
} else {
const percentageImprovement =
((worst[metricName] - best[metricName]) / worst[metricName]) * 100;
console.log(
`Best performing: ${best.url} (${best[metricName].toFixed(2)})`
);
console.log(
`Worst performing: ${worst.url} (${worst[metricName].toFixed(2)})`
);
console.log(
`Percentage improvement of best over worst: ${percentageImprovement.toFixed(
2
)}%`
);
}
}
const urls = ["https://www.disney.com/", "https://www.hbo.com/"];
console.log("Starting PageSpeed Insights analysis...");
const results = await Promise.all(urls.map(url => fetchPageSpeedData(url)));
console.log("All API calls completed. Processing results...");
const metrics = results.map(extractMetrics).filter(Boolean);
if (metrics.length === 0) {
throw new Error("No valid data received from any URL");
}
compareMetrics(metrics, "cls");
compareMetrics(metrics, "inp");
compareMetrics(metrics, "lcp");
compareMetrics(metrics, "performanceScore");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment