-
Notifications
You must be signed in to change notification settings - Fork 86
/
largest-contentful-paint.js
64 lines (53 loc) 路 1.69 KB
/
largest-contentful-paint.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
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const phone = devices.devicesMap['Nexus 5X'];
/**
* Measure LCP
*/
function calculateLCP() {
window.largestContentfulPaint = 0;
const observer = new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1];
window.largestContentfulPaint = lastEntry.renderTime || lastEntry.loadTime;
});
observer.observe({type: 'largest-contentful-paint', buffered: true});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
observer.takeRecords();
observer.disconnect();
console.log('LCP:', window.largestContentfulPaint);
}
});
}
/**
* Get LCP for a provided URL
* @param {*} url
* @return {Number} lcp
*/
async function getLCP(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);
await page.evaluateOnNewDocument(calculateLCP);
await page.goto(url, {waitUntil: 'load', timeout: 60000});
const lcp = await page.evaluate(() => {
return window.largestContentfulPaint;
});
browser.close();
return lcp;
} catch (error) {
console.log(error);
browser.close();
}
}
getLCP('https://pptr.dev').then((lcp) => console.log('LCP is: ' + lcp));