Skip to content

Instantly share code, notes, and snippets.

@nucliweb
Created May 25, 2022 17:22
Show Gist options
  • Save nucliweb/0b3917624353addd4dbd1c70dbc4fb9f to your computer and use it in GitHub Desktop.
Save nucliweb/0b3917624353addd4dbd1c70dbc4fb9f to your computer and use it in GitHub Desktop.
CSS Coverage
const puppeteer = require("puppeteer");
// const crawlPage = require("./crawl-urls");
const PAGE_URL = process.argv[2] || "https://pptr.dev";
const bytesToSize = (bytes, decimals = 2) => {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
};
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Gather coverage for CSS files
await Promise.all([page.coverage.startCSSCoverage()]);
await page.goto(PAGE_URL);
// Stops the coverage gathering
const [cssCoverage] = await Promise.all([page.coverage.stopCSSCoverage()]);
// Calculates # bytes being used based on the coverage
const calculateUsedBytes = (type, coverage) =>
coverage.map(({ url, ranges, text }) => {
let usedBytes = 0;
ranges.forEach((range) => (usedBytes += range.end - range.start - 1));
return {
url,
type,
usedBytes,
totalBytes: text.length,
percentUsed: `${((usedBytes / text.length) * 100).toFixed(2)}%`,
};
});
const calculateUsedBytesCssCoverage = [
...calculateUsedBytes("css", cssCoverage),
];
// calculateUsedBytesCssCoverage.map((cssResource) => {
// if (cssResource.usedBytes === 0) console.log(cssResource);
// });
const unusedCssResources = calculateUsedBytesCssCoverage.filter(
(cssResource) => cssResource.usedBytes === 0
);
const totalUnusedBytes = unusedCssResources
.map((cssResource) => cssResource.totalBytes)
.reduce((acc, cur) => acc + cur, 0);
console.log(unusedCssResources);
console.log("Total Unused CSS:", bytesToSize(totalUnusedBytes));
await browser.close();
})();
{
"name": "webperf-puppeteer",
"version": "1.0.0",
"description": "Web Performance Puppeteer Scripts",
"main": "index.js",
"scripts": {
"test": "node ./css-coverage.js https://joanleon.dev"
},
"keywords": [
"webperf",
"performacne",
"puppeteer",
"wpo"
],
"author": "Joan Leon | @nucliweb",
"license": "MIT",
"dependencies": {
"puppeteer": "^9.1.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment