Skip to content

Instantly share code, notes, and snippets.

@mcspx
Forked from schnerd/lazy-load-puppeteer.js
Created October 2, 2019 20:53
Show Gist options
  • Save mcspx/041e3241f9eb1c718b414f759a4aab46 to your computer and use it in GitHub Desktop.
Save mcspx/041e3241f9eb1c718b414f759a4aab46 to your computer and use it in GitHub Desktop.
Lazy-loading content in Puppeteer
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'});
}
@ammaarrrrr
Copy link

ammaarrrrr commented Oct 11, 2019

Hey. I'm using the code below to take screenshots using Puppeteer. Would love to know how i can integrate the code above in my own little piece of code:

const puppeteer = require('puppeteer');
async function run() {
    let browser = await puppeteer.launch({ headless: false });
    let page = await browser.newPage();
    await page.goto('https://google.com/', {waitUntil: 'load'});
    await page.screenshot({ path: './image1.png', type: 'png', fullPage: true });
    await page.close();
    await browser.close();
}
run();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment