Skip to content

Instantly share code, notes, and snippets.

@dwsmart
Last active January 23, 2020 17:08
Show Gist options
  • Save dwsmart/9f5abfc91fc1382dce55dc9804b0136e to your computer and use it in GitHub Desktop.
Save dwsmart/9f5abfc91fc1382dce55dc9804b0136e to your computer and use it in GitHub Desktop.
Cumulative Shift Example
const puppeteer = require('puppeteer');
/* variables to allow for user-agent / device.
example use: URL='https://tamethebots.com' useragent='Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' viewportw=412 viewporth=732 node shift.js
*/
const url = process.env.URL || 'https://tamethebots.com/';
const useragent = process.env.useragent || 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
const viewportw = process.env.viewportw || 412;
const viewporth = process.env.viewporth || 732;
const threeGee = {
'offline': false,
'downloadThroughput': 1.5 * 1024 * 1024 / 8,
'uploadThroughput': 750 * 1024 / 8,
'latency': 40
};
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setUserAgent(useragent);
await page.setViewport({
width: parseInt(viewportw),
height: parseInt(viewporth)
});
const client = await page.target().createCDPSession();
await client.send('Network.enable');
await client.send('Network.emulateNetworkConditions', threeGee);
await client.send('Emulation.setCPUThrottlingRate', {
rate: 4
});
try {
// load page
await page.goto(url);
/// evaluate Cumlative Shift, do in a promise race so returns undefined after 5 seconds as 0 shift situations never resolve otherwise
const shift = await Promise.race([page.evaluate(() => {
return new Promise(resolve => {
var CLS = 0;
new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
if (entry.hadRecentInput) return;
CLS += parseFloat(entry.value);
});
resolve(CLS);
}).observe({
type: "layout-shift",
buffered: true
});
});
}),
page.waitFor(5000)
]);
await browser.close();
if (!shift) {
console.log('0')
} else {
console.log(shift)
}
} catch (err) {
console.log('Error loading page:', err);
await browser.close();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment