Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Get the Percentage of Unused JS on a page with Puppeteer

    Tyler ClarkTyler Clark

    It can be helpful when automating tests, metrics, and integration tools to know not only how much JavaScript there is on a page but to calculate how much is not being used. We are able to calculate the percentage of JS used by getting metrics from the window object.

    puppeteerPuppeteer
    javascriptJavaScript
    chromeChrome
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 The first thing we need to do is install Puppeteer. Then inside of our file where we're using Puppeteer, we need to require it. I've made this function, getPageMetrics, which is async. The first thing we do is create a browser instance.

    00:14 With headless as false, it means that we're going to be able to see our Chromium browser open, and walk through the steps that we tell it to. Next, we will create a new page of our browser. We will navigate to google.com, and then close the browser.

    00:30 The first thing we need to do is do const response equals await, client send, performance.getMetrics. Then let's just console.log this response, so we can see what it looks like. If we run this file in our terminal, we'll see a browser open in the background, and we'll console.log an array full of objects.

    00:49 These objects have a bunch of metrics for us to use. For example, the amount of nodes that are on the page, some duration values, as well as the JS heap use size, and the total size. We'll use these two to calculate the unused JavaScript on the page.

    01:06 To calculate that, we'll do const jsUseSize equals response, metrics.find. Then we're going to look on the name property, JS heap use size, grab the value of it. Then const jsTotalSize equals response, metrics.find. We'll look for the name, JS heap total size, and grab that value.

    01:31 Next, we'll do const usedJS equals math.round, JS use size over JS total size, times 100. Now that we've plucked out the used JS and the total amount of JS used on the page, we can divide the used over the total, times it by 100, and round it out.

    01:52 Now, we can finish by console.logging 100 minus usedJS, percent of JS is unused. We could run this file in our terminal, and see that 36 percent of the JS is unused on the page.

    Discuss

    Discuss