Yes, it is possible to use Playwright for performance testing. Playwright is a Node.js library to automate the Chromium, WebKit, and Firefox browsers with a single API. Playwright is capable of measuring the performance of web pages by using browser APIs like PerformanceObserver and PerformanceNavigationTiming.
Let's see how we can use it to test the performance of a website.
JavaScript Example:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://yourwebsite.com');
const performanceTiming = JSON.parse(
await page.evaluate(() => JSON.stringify(window.performance.timing))
);
console.log(performanceTiming);
await browser.close();
})();
In this example, we are launching a Chromium browser, opening a new page, and navigating to 'https://yourwebsite.com'. The performance timing information is then logged onto the console. This information includes various timings related to the loading of the page, such as the time taken to connect to the server, the time taken to load the response, etc.
Python Example:
Playwright also provides a Python client. Here's how you can do the same thing in Python.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://yourwebsite.com')
performance_timing = page.evaluate('JSON.stringify(window.performance.timing)')
print(performance_timing)
browser.close()
This script does the same thing as the JavaScript version: it launches a Chromium browser, opens a new page, navigates to 'https://yourwebsite.com', and prints the performance timing information.
Remember, these scripts will give you raw performance timing data. To turn this data into something useful, you will need to process it to calculate metrics like TTFB (Time to First Byte), FCP (First Contentful Paint), and LCP (Largest Contentful Paint).