Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Lazy loading

How to Use PhantomJS to Screenshot Pages with Lazy-Loaded Images

By Freedom251 Team · · 5 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To capture lazy-loaded images with PhantomJS, open the page with JavaScript and image loading enabled, scroll down in viewport-sized steps, pause so each step can trigger image requests, check that images have loaded, and only then call page.render(). This is a best-effort legacy technique: PhantomJS development is suspended, and scrolling cannot guarantee that every site will load every image.

Why images are missing from a PhantomJS screenshot

Many pages defer fetching offscreen images until they approach the viewport. A screenshot taken immediately after the page opens may therefore show blank spaces where images have not yet been requested or rendered. Scrolling the page gives viewport- and scroll-triggered loading code a chance to run; it does not make failed requests succeed or cover every site-specific loading technique. Google Chrome Developers’ overview of browser-level image lazy loading explains the viewport relationship and notes that images likely to appear in the first viewport should not be lazy-loaded.

As an Amazon Associate I earn from qualifying purchases.

Run a scroll, wait, inspect, and render workflow

Here is a PhantomJS script that opens a URL, advances down the page in overlapping viewport steps, waits briefly after each step, checks image completion, and renders after a final settling period. Save it as lazy-shot.js and run it with the PhantomJS executable available on your system:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var page = require('webpage').create();
var system = require('system');
var address = system.args[1];
var output = system.args[2] || 'screenshot.png';

if (!address) {
  console.log('Usage: phantomjs lazy-shot.js <url> [output.png]');
  phantom.exit(2);
}

page.viewportSize = { width: 1280, height: 800 };
page.settings.javascriptEnabled = true;
page.settings.loadImages = true;

var stepDelayMs = 400;
var finalDelayMs = 1200;
var scrollY = 0;
var viewportHeight = page.viewportSize.height;

page.onConsoleMessage = function (message) {
  console.log('PAGE:', message);
};
page.onResourceError = function (error) {
  console.log('RESOURCE ERROR:', error.url, error.errorString);
};

function finishCapture() {
  window.setTimeout(function () {
    var imageState = page.evaluate(function () {
      var images = Array.prototype.slice.call(document.images);
      return {
        count: images.length,
        incomplete: images.filter(function (img) {
          return !img.complete || img.naturalWidth === 0;
        }).map(function (img) {
          return img.currentSrc || img.src || img.getAttribute('data-src') || '(no URL)';
        })
      };
    });

    console.log('Images found:', imageState.count);
    if (imageState.incomplete.length) {
      console.log('Images not confirmed loaded:', JSON.stringify(imageState.incomplete));
    }

    var rendered = page.render(output);
    console.log(rendered ? 'Saved ' + output : 'Render failed: ' + output);
    phantom.exit(rendered ? 0 : 1);
  }, finalDelayMs);
}

function scrollNext() {
  var metrics = page.evaluate(function (nextY) {
    window.scrollTo(0, nextY);
    return {
      y: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
      height: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
      viewport: window.innerHeight
    };
  }, scrollY);

  if (metrics.y + metrics.viewport >= metrics.height) {
    finishCapture();
    return;
  }

  scrollY = metrics.y + Math.max(1, Math.floor(viewportHeight * 0.8));
  window.setTimeout(scrollNext, stepDelayMs);
}

page.open(address, function (status) {
  if (status !== 'success') {
    console.log('Page open failed:', status);
    phantom.exit(1);
    return;
  }

  scrollNext();
});

Example invocation: phantomjs lazy-shot.js https://example.com output.png. The script sets the viewport and page settings before page.open(), waits for the open callback, scrolls with overlap, then inspects images. Its delay values are starting points to tune for the site; they are not guarantees that a request has completed. The image check flags images that are incomplete or have a zero naturalWidth at inspection time, but a site may use CSS backgrounds, custom attributes, or later JavaScript changes that this check does not cover.

#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB | 1920×1080 LED Monitor, 4ms GtG, Adaptive Sync, HDMI 1.4, Tilt Adjust, Low Blue Light, 4yr Advance Replacement Warranty
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Why the evaluated code is deliberately small

page.evaluate() runs in the page’s context. It cannot access PhantomJS-side variables or pass DOM nodes back to the PhantomJS script; pass simple JSON-compatible arguments and return simple JSON-compatible values instead. The PhantomJS documentation describes this sandbox behavior in the evaluate API.

Choose the capture dimensions and output deliberately

page.render() writes the rendered page to a file. The documented formats include PDF, PNG, JPEG, BMP, and PPM; GIF support depends on the Qt build. A viewport-sized capture and a full-page capture are different outcomes. PhantomJS’s screen-capture guide covers viewport dimensions and clipping with clipRect. Confirm the output dimensions and clipping behavior in the PhantomJS build you deploy rather than assuming that a tall viewport will produce the same full-page result everywhere. See the render API for the method’s documented options.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB | 1920×1080 LED Monitor, 4ms GtG, Adaptive Sync, HDMI 1.4, Tilt Adjust, Low Blue Light, 4yr Advance Replacement Warranty
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Settings, reliability, and compatibility limits

PhantomJS documents javascriptEnabled and loadImages as enabled by default. Set them before navigation if you want to make the intended behavior explicit: page settings apply during the initial page.open(), and changing them afterward does not affect that initial navigation. The page settings documentation lists these properties.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The scrolling loop is a practical technique, not a built-in PhantomJS guarantee. A page can load images only after a click, use custom lazy-loading attributes, change image URLs dynamically, or encounter network failures. The script reports incomplete image elements rather than treating page-open success as proof that every image is ready. For a site you control, disabling lazy loading for the capture route or exposing an explicit page-ready signal can be more reliable than guessing at delays.

Rank #3
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

PhantomJS’s homepage states, “Important: PhantomJS development is suspended until further notice,” and identifies QtWebKit as its backend. Current JavaScript and browser API compatibility should not be assumed; no current compatibility matrix is established here. For a new workflow, evaluate whether a maintained browser automation option better fits your target sites, especially if they depend on modern browser features.

Troubleshoot missing images or failed captures

  • Images remain blank after scrolling: Increase the per-step and final wait periods, then inspect the reported incomplete URLs and resource errors. A longer delay helps only if requests are still in progress; it will not fix a failed request.
  • The page opens but does not look like a modern browser: The page may depend on browser APIs or JavaScript unsupported by PhantomJS’s QtWebKit backend. Check the page’s console and resource errors, and consider whether a maintained browser automation runtime is needed.
  • Some images are absent from the image check: The page may use CSS background images or custom attributes rather than ordinary <img> elements. The script’s document.images check is not a complete inventory of visual assets.
  • The output is clipped or not full-page: Review the configured viewport and clipRect behavior in the deployed build, and inspect the actual image dimensions. A viewport capture should not be mistaken for a full-page capture.
  • The script reports page-open failure: Check the URL, network access, and PhantomJS console/resource errors. Do not render on a failed open and assume the result is valid.

Or skip the browser setup

For a one-request alternative, ScreenshotNeo returns a screenshot or PDF from a URL. See the ScreenshotNeo website and API documentation for request details.

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor | 100Hz, Game Mode, Advanced Eye Comfort, HDMI and D-sub Ports (LS27D366GANXZA)
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers indicate the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 screenshots per month with no card required; paid plans start at $5 for 3,000 screenshots.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a free ScreenshotNeo account to start with 1,000 screenshots a month and no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Frequently Asked Questions

Can PhantomJS guarantee that every lazy-loaded image appears?

No. Scrolling gives viewport-triggered loaders a chance to run, but site-specific behavior, interactions, and failed requests can still leave images missing.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Does PhantomJS development continue?

No. The PhantomJS homepage says development is suspended until further notice.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Lazy loadingPhantomJSscreenshotsweb automation

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.