-
Notifications
You must be signed in to change notification settings - Fork 90
/
cumulative-layout-shift.js
69 lines (58 loc) · 1.9 KB
/
cumulative-layout-shift.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const phone = devices.devicesMap['Nexus 5X'];
/**
* Measure layout shifts
*/
function calculateShifts() {
window.cumulativeLayoutShiftScore = 0;
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
console.log('New observer entry for cls: ' + entry.value);
window.cumulativeLayoutShiftScore += entry.value;
}
}
});
observer.observe({type: 'layout-shift', buffered: true});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
observer.takeRecords();
observer.disconnect();
console.log('CLS:', window.cumulativeLayoutShiftScore);
}
});
}
/**
* Get cumulative layout shift for a URL
* @param {String} url - url to measure
* @return {Number} - cumulative layout shift
*/
async function getCLS(url) {
const browser = await puppeteer.launch({
args: ['--no-sandbox'],
timeout: 10000,
});
try {
const page = await browser.newPage();
const client = await page.target().createCDPSession();
await client.send('Network.enable');
await client.send('ServiceWorker.enable');
await page.emulateNetworkConditions(puppeteer.networkConditions['Good 3G']);
await page.emulateCPUThrottling(4);
await page.emulate(phone);
// inject a function with the code from
// https://web.dev/cls/#measure-cls-in-javascript
await page.evaluateOnNewDocument(calculateShifts);
await page.goto(url, {waitUntil: 'load', timeout: 60000});
const cls = await page.evaluate(() => {
return window.cumulativeLayoutShiftScore;
});
browser.close();
return cls;
} catch (error) {
console.log(error);
browser.close();
}
}
getCLS('https://pptr.dev').then((cls) => console.log('CLS is: ' + cls));