Instructor: to get up and running with Google Puppeteer, we need to do const puppeteer equals required puppeteer. Then, we'll do const get page metrics as an async function. Do const browser equals await puppeteer launch with the headless property of false and cont page equals a weight browser.new page.
With Puppeteer in our context, we can launch a Chromium browser. Because headless is false, when we run this file, it's going to open up an instance of Chromium and perform the actions we defined for us to see.
Let's begin by getting metrics about our page's CSS. Let's do await page client.sand dom.enable await page client.send CSS enable await page client.send CSS.start role uses tracking. Await page client.sand performance enable. Const style sheets equals an array. Page client on CSS style sheet added, do a callback. We'll push our headers into our style sheet array. Then, we'll go to just google.com. Perfect.
Now in order to get metrics from the dev tools, we need to message out commands. The Chrome dev tools is a single page app that communicates with Chrome. In order to get any metrics, we need to know which commands to send. In our case, we're dom, CSS, and performance enablement messages. This is so we can collect data on CSS. Then, we listen for style sheets that are added to the page and add them to an array.
Then after navigating to google.com, we need to destructure role usage from await page client send CSS.stop rule usage tracking. Now that we've started tracking, navigated to our page, then stopped tracking, we have both a number of style sheets added and the rule usage for each of those style sheets.
Let's do const unused CSS equals calc CSS.unused CSS style sheets enroll usage. Do a constant out log, a new CSS, percent of CSS is unused. Style sheets.length total style sheets then browser.close. Awesome.
When we send the stop rule usage tracking command, we receive a response back. With rule usage, we're able to check against the style sheets we've collected the total amount of CSS in those style sheets and what CSS was actually used.
I've gone ahead and created a couple functions inside of calc CSS that go through both the rule usage and our style sheets from the page. In unused CSS, we're gathering the use CSS and the total from each style sheet. In order to get the total use CSS, we need to filter on the rule usage and the style sheet's IDs, then return a total number of CSS. Finally, we return the rounded percentage.
After we require our calc CSS from our calc CSS.js file, we can invoke this function and run it in our terminal. Let's run Node metrics.js. We'll see a Chromium browser open up in the background. We'll see that we get 85 percent of the CSS is unused. There's 13 total style sheets...