-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add command to benchmark Web Vitals via web-vitals
library
#40
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f3c7047
Rename benchmark-url to benchmark-server-timing.
felixarntz d4d2731
Remove example link since the benchmark-server-timing command is alre…
felixarntz 378f8b6
Make getURLs a reusable function.
felixarntz a4b2c7b
Install Puppeteer.
felixarntz a71c443
Implement first working version of benchmark-web-vitals command.
felixarntz e773bd4
Make JS import dynamic.
felixarntz 1d160f4
Limit metrics to only load time metrics for now.
felixarntz a141164
Add documentation for new command.
felixarntz 52f5570
Add link to follow up PR.
felixarntz 536f4f8
Add link to follow up PR.
felixarntz 582aaa6
Clarify comment.
felixarntz afa6239
Fix grammar mistake in param docs.
felixarntz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,220 @@ | ||
/** | ||
* CLI command to benchmark several URLs for Core Web Vitals and other key metrics. | ||
* | ||
* WPP Research, Copyright 2023 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
/** | ||
* External dependencies | ||
*/ | ||
import puppeteer from 'puppeteer'; | ||
import round from 'lodash-es/round.js'; | ||
|
||
/** | ||
* Internal dependencies | ||
*/ | ||
import { getURLs } from '../lib/cli/args.mjs'; | ||
import { | ||
log, | ||
formats, | ||
table, | ||
isValidTableFormat, | ||
OUTPUT_FORMAT_TABLE, | ||
} from '../lib/cli/logger.mjs'; | ||
import { calcMedian } from '../lib/util/math.mjs'; | ||
|
||
export const options = [ | ||
{ | ||
argname: '-u, --url <url>', | ||
description: 'A URL to run benchmark tests for', | ||
}, | ||
{ | ||
argname: '-n, --number <number>', | ||
description: 'Number of requests to perform', | ||
defaults: 1, | ||
}, | ||
{ | ||
argname: '-f, --file <file>', | ||
description: 'File with URLs to run benchmark tests for', | ||
}, | ||
{ | ||
argname: '-o, --output <output>', | ||
description: 'Output format: csv or table', | ||
defaults: OUTPUT_FORMAT_TABLE, | ||
}, | ||
]; | ||
|
||
export async function handler( opt ) { | ||
if ( ! isValidTableFormat( opt.output ) ) { | ||
log( | ||
formats.error( | ||
'The output format provided via the --output (-o) argument must be either "table" or "csv".' | ||
) | ||
); | ||
return; | ||
} | ||
|
||
const { number: amount } = opt; | ||
const results = []; | ||
|
||
const browser = await puppeteer.launch(); | ||
|
||
for await ( const url of getURLs( opt ) ) { | ||
const { completeRequests, metrics } = await benchmarkURL( | ||
browser, | ||
{ | ||
url, | ||
amount, | ||
} | ||
); | ||
|
||
results.push( [ url, completeRequests, metrics ] ); | ||
} | ||
|
||
await browser.close(); | ||
|
||
if ( results.length === 0 ) { | ||
log( | ||
formats.error( | ||
'You need to provide a URL to benchmark via the --url (-u) argument, or a file with multiple URLs via the --file (-f) argument.' | ||
) | ||
); | ||
} else { | ||
outputResults( opt, results ); | ||
} | ||
} | ||
|
||
async function benchmarkURL( browser, params ) { | ||
/* | ||
* For now this only includes load time metrics. | ||
* In the future, additional Web Vitals like CLS, FID, and INP should be | ||
* added, however they are slightly more complex to retrieve through an | ||
* automated headless browser test. | ||
* See https://github.com/GoogleChromeLabs/wpp-research/pull/41. | ||
*/ | ||
const metricsDefinition = { | ||
FCP: { | ||
listen: 'onFCP', | ||
global: 'webVitalsFCP', | ||
get: () => window.webVitalsFCP, | ||
results: [], | ||
}, | ||
LCP: { | ||
listen: 'onLCP', | ||
global: 'webVitalsLCP', | ||
get: () => window.webVitalsLCP, | ||
results: [], | ||
}, | ||
TTFB: { | ||
listen: 'onTTFB', | ||
global: 'webVitalsTTFB', | ||
get: () => window.webVitalsTTFB, | ||
results: [], | ||
}, | ||
}; | ||
|
||
let completeRequests = 0; | ||
let requestNum = 0; | ||
|
||
let scriptTag = `import { ${ Object.values( metricsDefinition ).map( ( value ) => value.listen ).join( ', ' ) } } from "https://unpkg.com/web-vitals@3?module";`; | ||
Object.values( metricsDefinition ).forEach( ( value ) => { | ||
scriptTag += `${ value.listen }( ( { name, delta } ) => { window.${ value.global } = name === 'CLS' ? delta * 1000 : delta; } );`; | ||
} ) | ||
|
||
for ( requestNum = 0; requestNum < params.amount; requestNum++ ) { | ||
const page = await browser.newPage(); | ||
|
||
// Set viewport similar to @wordpress/e2e-test-utils 'large' configuration. | ||
await page.setViewport( { width: 960, height: 700 } ); | ||
await page.mainFrame().waitForFunction( 'window.innerWidth === 960 && window.innerHeight === 700' ); | ||
|
||
// Load the page. | ||
const response = await page.goto( `${ params.url }?rnd=${ requestNum }`, { waitUntil: 'networkidle0' } ); | ||
await page.addScriptTag( { content: scriptTag, type: 'module' } ); | ||
|
||
if ( response.status() !== 200 ) { | ||
continue; | ||
} | ||
|
||
completeRequests++; | ||
|
||
await Promise.all( | ||
Object.values( metricsDefinition ).map( async ( value ) => { | ||
// Wait until global is populated. | ||
await page.waitForFunction( `window.${ value.global } !== undefined` ); | ||
|
||
/* | ||
* Do a random click, since only that triggers certain metrics | ||
* like LCP, as only a user interaction stops reporting new LCP | ||
* entries. See https://web.dev/lcp/. | ||
*/ | ||
await page.click( 'body' ); | ||
|
||
// Get the metric value from the global. | ||
const metric = await page.evaluate( value.get ); | ||
value.results.push( metric ); | ||
} ) | ||
).catch( ( err ) => { /* Ignore errors. */ } ); | ||
} | ||
|
||
const metrics = {}; | ||
Object.entries( metricsDefinition ).forEach( ( [ key, value ] ) => { | ||
if ( value.results.length ) { | ||
metrics[ key ] = value.results; | ||
} | ||
} ); | ||
|
||
return { completeRequests, metrics }; | ||
} | ||
|
||
function outputResults( opt, results ) { | ||
const len = results.length; | ||
const allMetricNames = {}; | ||
|
||
for ( let i = 0; i < len; i++ ) { | ||
for ( const metric of Object.keys( results[ i ][ 2 ] ) ) { | ||
allMetricNames[ metric ] = ''; | ||
} | ||
} | ||
|
||
const headings = [ | ||
'URL', | ||
'Success Rate', | ||
...Object.keys( allMetricNames ), | ||
]; | ||
|
||
const tableData = []; | ||
|
||
for ( let i = 0; i < len; i++ ) { | ||
const [ url, completeRequests, metrics ] = results[ i ]; | ||
const completionRate = round( | ||
( 100 * completeRequests ) / ( opt.number || 1 ), | ||
1 | ||
); | ||
|
||
const vals = { ...allMetricNames }; | ||
for ( const metric of Object.keys( metrics ) ) { | ||
vals[ metric ] = `${ round( calcMedian( metrics[ metric ] ), 2 ) }`; | ||
} | ||
|
||
tableData.push( [ | ||
url, | ||
`${ completionRate }%`, | ||
...Object.values( vals ), | ||
] ); | ||
} | ||
|
||
log( table( headings, tableData, opt.output, true ) ); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FID and INP are more complex as require an interaction, but the load CLS should be similar to FCP/LCP/TTFB shouldn't it?
Granted, that often isn't the full CLS of a page (as it can be impacted by scroll, or other interactions), but it's still usually a good part of CLS. And that "load CLS" is what Lighthouse and PSI already captures despite it's limitations.
The only thing is that, kind of like LCP, CLS is not emitted by web-vitals.js, until the page is hidden (including navigating away from it). For the web-vitals.js library we dummy this visibility change:
https://github.com/GoogleChrome/web-vitals/blob/main/test/utils/stubVisibilityChange.js
And then call it like this:
Maybe that's enough to make it too complicated here?
The alternative is to use the
reportAllChanges
flag and only report at the end of the test.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @tunetheweb, that it great context. I am a bit unsure about CLS being more similar to the load time metrics; based on what you're saying it makes sense, but when I initially tried using all of them, I always got data for FID actually but not CLS.
In any case, I think due to those additional complexities it makes sense to separate the work into more incremental steps, and I think starting with only FCP/LCP/TTFB works well as those are all load time metrics and they are simplest to implement here. #41 covers the follow up work, so I'd prefer to handle CLS, FID, and INP in that (or maybe even broken down into further separated PRs).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah sounds like it’s due to not changing the visibility so CLS not being “finalised”. Which I realised and edited after writing that first sentence (but before submitting the review).