-
-
Save by-nari/afae630a68a0f39bffb6fa07fd095699 to your computer and use it in GitHub Desktop.
Lazy-loading content in Puppeteer
This file contains hidden or 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
function wait (ms) { | |
return new Promise(resolve => setTimeout(() => resolve(), ms)); | |
} | |
export default async function capture(browser, url) { | |
// Load the specified page | |
const page = await browser.newPage(); | |
await page.goto(url, {waitUntil: 'load'}); | |
// Get the height of the rendered page | |
const bodyHandle = await page.$('body'); | |
const { height } = await bodyHandle.boundingBox(); | |
await bodyHandle.dispose(); | |
// Scroll one viewport at a time, pausing to let content load | |
const viewportHeight = page.viewport().height; | |
let viewportIncr = 0; | |
while (viewportIncr + viewportHeight < height) { | |
await page.evaluate(_viewportHeight => { | |
window.scrollBy(0, _viewportHeight); | |
}, viewportHeight); | |
await wait(20); | |
viewportIncr = viewportIncr + viewportHeight; | |
} | |
// Scroll back to top | |
await page.evaluate(_ => { | |
window.scrollTo(0, 0); | |
}); | |
// Some extra delay to let images load | |
await wait(100); | |
return await page.screenshot({type: 'png'}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment