Skip to content

Instantly share code, notes, and snippets.

@schnerd
Created April 18, 2018 03:21
Show Gist options
  • Save schnerd/b550b7c05d4a57d8374082aaae714881 to your computer and use it in GitHub Desktop.
Save schnerd/b550b7c05d4a57d8374082aaae714881 to your computer and use it in GitHub Desktop.

Revisions

  1. schnerd created this gist Apr 18, 2018.
    35 changes: 35 additions & 0 deletions lazy-load-puppeteer.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    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'});
    }