Get the Percentage of Unused JS on a page with Puppeteer

Tyler Clark
InstructorTyler Clark

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

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.

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, 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.

Kara Schaefer
Kara Schaefer
~ 4 years ago

Hi Tyler. Thanks a bunch for this video. I am not sure I am able to interpret the data in a meaningful way. For example I have a simple static site as my personal page right now (, and I don't even have any .js files, yet it still tells me that 45% of the JS is unused. Can you help me understand?