DEV Community

Benjamin Mock
Benjamin Mock

Posted on

5

πŸš€ Performance measuring of a webpage with JavaScript in Node.js using puppeteer

In the last part of my puppeteer series, we learned how to execute JavaScript in a page context. We'll now use this knowledge to actually do something useful: we'll measure the load time of the loaded webpage. In our case, that's the load time of dev.to.

We'll focus on just the load time. But performance.timing has many more properties. Just try to log them on your console to learn more.

Here's the complete code to measure the load time of a webpage using puppeteer. This could, for example, be used for continuous measuring of load times, or be added as a pre-push hook.

// npm i puppeteer
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // let's navigate to the dev.to homepage
  await page.goto('https://dev.to');

  // evaluate will run the function in the page context
  const perf = await page.evaluate(_ => {
    // let's get the latency-related performance information
    const { loadEventEnd, navigationStart } = performance.timing;

    // calculate the load time in milliseconds
    return { loadTime: loadEventEnd - navigationStart };
  });

  // and log the load time of the webpage
  console.log(perf.loadTime);

  // we're done; close the browser
  await browser.close();
})();
Enter fullscreen mode Exit fullscreen mode

Please consider following me, if you're interested in measuring the performance of webpages. I'll post more about that topic in this and other series.

Thanks for reading!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’