Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk6 min

How to Wait for Images to Load Before a Playwright Screenshot

Wait for the image elements your screenshot depends on, decide whether broken images should fail, trigger lazy loading, then capture with Playwright.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use page.waitForFunction() to check the images your screenshot needs, then capture the page with page.screenshot(). The key choice is whether a failed image counts as “finished” or should fail your check: image.complete covers both successful and failed loads, while image.complete && image.naturalWidth > 0 requires a successfully loaded image.

Wait for the images before capturing

Here is a minimal JavaScript example using Playwright’s Page API:

As an Amazon Associate I earn from qualifying purchases.

await page.goto(url);

await page.waitForFunction(() =>
  [...document.images].every(image => image.complete)
);

await page.screenshot({ path: 'page.png' });

page.goto() waits for the document’s load event by default. The image predicate adds a separate check for the current document images before the screenshot. Playwright documents waitForFunction() and screenshot() in its Page API; the image predicate is application-level logic built on that API, not a prescribed Playwright image-wait helper.

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

Choose what “loaded” means for your test

Wait until every current image has finished

Use image.complete when the requirement is that no current image remains pending. A completed image may have failed to load, so this condition does not prove that its pixels are available.

await page.waitForFunction(() =>
  [...document.images].every(image => image.complete)
);

Require successful image resources

For visual tests where a broken image is a defect, require a positive natural width. This waits until each current document image is complete and has a successful image resource:

await page.waitForFunction(() =>
  [...document.images].every(image =>
    image.complete && image.naturalWidth > 0
  )
);

This condition can time out if even one image is broken. That may be the right result for a regression test; for a resilience check or scraper, record which resources failed and decide whether to proceed rather than treating every failure as fatal.

Limit the check to the images that matter

Waiting on every image in document.images may be too strict for a screenshot of one component, and it does not include images inside other browsing contexts. Select the intended set instead. For example, check images in a known section:

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.
await page.waitForFunction(() => {
  const section = document.querySelector('#product-gallery');
  if (!section) return false;

  return [...section.querySelectorAll('img')].every(image =>
    image.complete && image.naturalWidth > 0
  );
});

Adapt the selector and success rule to the page. If the application replaces image sources during hydration or inserts images asynchronously, ensure your check runs against the final intended set rather than assuming the first set of elements will remain unchanged.

Set a finite timeout and diagnose failures

A bounded wait prevents a screenshot task from hanging indefinitely. Playwright’s waitForFunction() accepts an options object; the example below sets a 10-second timeout:

await page.waitForFunction(
  () => [...document.images].every(image => image.complete),
  { timeout: 10_000 }
);

If it times out, identify the condition that remains false instead of simply raising the timeout. Check whether an image request failed, whether the page changes image sources after hydration, or whether a lazy image has not yet been requested. For a test that requires successful resources, a broken image will also keep the positive-naturalWidth condition false.

Trigger lazy-loaded images before waiting

Full-page capture does not by itself establish that every offscreen lazy image has been requested and loaded. If the page loads images as they approach the viewport, trigger that behavior first—by scrolling through the page, or by scrolling the relevant container—then wait for the image set in the capture region.

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

For example, a simple page-wide scroll can bring below-the-fold content into view before checking images:

await page.goto(url);

await page.evaluate(async () => {
  const step = Math.max(1, window.innerHeight);
  for (let y = 0; y < document.body.scrollHeight; y += step) {
    window.scrollTo(0, y);
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  window.scrollTo(0, 0);
});

await page.waitForFunction(() =>
  [...document.images].every(image => image.complete)
);

await page.screenshot({ path: 'page.png', fullPage: true });

The short pauses in this example give page code opportunities to react to scrolling; they are not proof that images finished loading. The image predicate supplies that check. Pages with nested scroll containers or application-specific loading behavior may need a targeted scroll strategy. Validate the trigger against the application under test.

Use readiness conditions rather than network quietness

Playwright’s navigation milestones describe different stages: commit means the response was received and document loading started; domcontentloaded is earlier than the document load event. The default page.goto() wait is load, but even that is not a guarantee that the particular images your test needs have loaded successfully.

Playwright defines networkidle as no network connections for at least 500 ms, but discourages using it for testing and recommends relying on web assertions to assess readiness. Network quiet does not identify which images matter, and applications can defer work or continue changing content. Prefer a predicate tied to the image elements and outcome your screenshot requires.

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

Capture once the condition passes

For a screenshot file, take the capture immediately after your readiness check:

await page.screenshot({ path: 'page.png', fullPage: true });

For Playwright Test visual regression, expect(page).toHaveScreenshot() waits until two consecutive page screenshots yield the same result before comparing the last one with the expectation. That is a visual-stability mechanism, not a guarantee that a particular image loaded successfully. Pair it with an image readiness check when image presence is part of the test.

await page.waitForFunction(() =>
  [...document.images].every(image =>
    image.complete && image.naturalWidth > 0
  )
);

await expect(page).toHaveScreenshot('page.png');

Keep the browser and rendering environment consistent for comparisons: Playwright notes that operating system, browser version, settings, hardware, power source, and headless mode can affect rendering. See its visual comparisons guidance.

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

Troubleshoot common image-wait problems

  • The wait times out with complete. One or more image elements may still be pending. Inspect their current URLs and loading behavior, and check whether the page replaces or adds images after navigation.
  • The wait times out only when checking naturalWidth. At least one current image may be broken or not yet successfully decoded into an image resource. Decide whether that should fail the test; if so, report the failed image rather than weakening the assertion blindly.
  • Below-the-fold images are missing from a full-page screenshot. Trigger the page’s lazy-loading behavior before waiting. Scroll the relevant container if the images are inside one, then check the intended elements.
  • The page has no images when the predicate first runs. The application may add them later. Wait for a page-specific readiness condition or for the intended container and its images to appear, then evaluate image state.
  • A longer fixed delay seems to help intermittently. Elapsed time does not establish that the required image requests completed. Use a finite predicate wait and investigate the image still pending or failing.

Or skip the browser setup

If you need a screenshot rather than a Playwright test, ScreenshotNeo provides a one-request website screenshot API. Its capture can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before the shot; those cleanup steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, with the outcome identified in response headers. It also offers an MCP server for AI agents using Claude, Cursor, or another MCP client.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Sign up for 1,000 free screenshots a month—no card required.

Frequently Asked Questions

Does `image.complete` mean the image loaded successfully?

No. It is true when loading has finished or failed. Check `image.naturalWidth > 0` as well when success is required.

Will `page.screenshot({ fullPage: true })` load lazy images automatically?

Do not rely on full-page capture alone to trigger every offscreen lazy image. Trigger the page’s lazy-loading behavior, then wait for the images your capture needs.

Is `networkidle` a reliable replacement for checking image state?

No. Playwright discourages `networkidle` for testing; use a readiness condition tied to the specific content the test needs.

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

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.

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.