Skip to content

Instantly share code, notes, and snippets.

@dwsmart
Last active December 1, 2020 11:19
Show Gist options
  • Save dwsmart/0af960697e0421a41608a77d04a77dcd to your computer and use it in GitHub Desktop.
Save dwsmart/0af960697e0421a41608a77d04a77dcd to your computer and use it in GitHub Desktop.
/*
usage:
node usedcss url=<page_to_test> filename=<required_file_name> viewport=<widthxheight> ua='<my user agent>'
filename, viewport & ua optional,
Example:
node usedcss url=https://tamethebots.com filename=ttb_used.css viewport=360x640 ua='css coverage script'
Updated to print original stylesheet URL
*/
const args = process.argv.slice(2);
const puppeteer = require('puppeteer');
const fs = require('fs');
let url = 'https://www.example.com';
let ua = 'default';
let filename = 'used.css';
let viewport = [800, 600];
if (args.find(v => v.includes('viewport='))) {
const vp = args.find(v => v.includes('viewport')).replace('viewport=', '').split('x');
viewport = [parseInt(vp[0]), parseInt(vp[1])];
}
if (args.find(v => v.includes('ua='))) {
ua = args.find(v => v.includes('ua=')).replace('ua=', '');
}
if (args.find(v => v.includes('url='))) {
url = args.find(v => v.includes('url=')).replace('url=', '');
}
if (args.find(v => v.includes('filename='))) {
filename = args.find(v => v.includes('filename=')).replace('filename=', '');
}
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await Promise.all([page.coverage.startCSSCoverage()]);
await page.goto(url, {
waitUntil: 'networkidle2'
});
const cssUsed = await Promise.all([page.coverage.stopCSSCoverage(), ]);
const covered = [...cssUsed];
let cleanCSS = "";
for (const cssEntries of covered[0]) {
cleanCSS += `/* file: ${cssEntries.url} */\n`
for (const range of cssEntries.ranges) {
cleanCSS += cssEntries.text.slice(range.start, range.end) + "\n";
}
}
fs.writeFile(`./${filename}`, cleanCSS, function(err) {
if (err) {
return console.log(err);
}
console.log(`${filename} saved`);
});
await browser.close();
}
)();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment