ScreenshotNeo

BlogHow-to

How to Wait for Images to Load Before Taking a Percy Snapshot?

Trigger lazy-loaded images, wait for a reliable readiness signal, and take a stable Percy snapshot with Cypress.

By the ScreenshotNeo team30 September 202610 min read

How to Wait for Images to Load Before Taking a Percy Snapshot?

To wait for images before a Percy snapshot, first scroll far enough to trigger lazy loading, then assert that the page’s images have finished loading and have a nonzero natural width. Call cy.percySnapshot() only after those checks pass:

cy.scrollTo('bottom');

cy.get('img').should(($imgs) => {
  for (const img of $imgs) {
    expect(img.complete, 'image complete').to.be.true;
    expect(img.naturalWidth, 'image has width').to.be.greaterThan(0);
  }
});

cy.percySnapshot('Lazy Loading - Fully Rendered');

This is Percy’s published Cypress pattern. Scrolling can trigger images loaded by an IntersectionObserver or scroll listener, and the assertions make the snapshot wait on image state instead of an arbitrary delay. Adapt the scroll and selector to match the page and the image implementation. Percy’s guide notes that it captures the DOM after the scroll and image checks complete.

1. Why images are missing from visual snapshots

Many pages do not fetch every image at initial render. Below-the-fold images may use native lazy loading, an IntersectionObserver, a component-level loader, or a scroll handler. They begin loading only when they approach the viewport or another configured loading boundary.

Scrolling can trigger below-the-fold lazy images; assert readiness before the Percy snapshot.
Scrolling can trigger below-the-fold lazy images; assert readiness before the Percy snapshot.

A visual test that snapshots immediately after navigation can therefore capture placeholders, blank image boxes, or only the images initially visible. A fixed delay may appear to help, but it does not ensure that the page reached the desired state: a slow response can outlast the delay, while a fast response leaves the test idle unnecessarily. Percy advises using an image readiness check rather than relying on a hard-coded wait as the main strategy.

The dependable sequence is: cause the page to request the images relevant to the snapshot, wait for an observable readiness condition, then snapshot. The condition must represent the page you intend to test. Checking every img is useful for ordinary image elements, but it does not automatically cover CSS backgrounds or custom image components.

2. Add the readiness gate to a Cypress test

Step 1: Make sure Percy is set up

Use the project’s existing Cypress and Percy setup, including the Percy Cypress integration and the project’s normal way of running visual tests. Percy’s Cypress overview covers that integration and snapshot workflow: Conducting Visual Testing With Cypress. Keep the test’s normal navigation, data setup, and authentication before the loading sequence.

The snapshot should run only after the selected images pass the readiness check.
The snapshot should run only after the selected images pass the readiness check.

Step 2: Trigger lazy loading

For a page whose below-the-fold content loads on scroll, scroll to the bottom before checking image state:

cy.visit('/gallery');
cy.scrollTo('bottom');

The scroll is a trigger, not proof of readiness. The page may load images asynchronously after the scroll event. If loading is triggered in viewport-sized increments, scroll through the page in steps instead of jumping directly to the bottom. That can also be necessary when the page only loads content near the current viewport.

Step 3: Assert the image state

For ordinary img elements, assert both complete and naturalWidth > 0:

cy.get('img').should(($imgs) => {
  for (const img of $imgs) {
    expect(img.complete, 'image complete').to.be.true;
    expect(img.naturalWidth, 'image has width').to.be.greaterThan(0);
  }
});

Cypress retries a should() callback while its assertions fail, subject to the command’s timeout. complete alone is not enough: a broken image can finish loading and still have no usable image width. Requiring a positive naturalWidth distinguishes a successfully decoded image from an unsuccessful load for this check.

Step 4: Take the snapshot after the gate

cy.percySnapshot('Lazy Loading - Fully Rendered');

Place the snapshot after the scroll and the passing assertions in the Cypress command chain. This ordering ensures the snapshot follows the readiness gate. The assertion is meaningful only for the elements it selects and the loading behavior it triggers.

Complete example

describe('gallery visual state', () => {
  it('captures the gallery after its images load', () => {
    cy.visit('/gallery');

    // Trigger lazy images below the initial viewport.
    cy.scrollTo('bottom');

    // Wait until each selected img has loaded successfully.
    cy.get('img').should(($imgs) => {
      expect($imgs.length, 'images on the page').to.be.greaterThan(0);

      for (const img of $imgs) {
        expect(img.complete, `complete: ${img.currentSrc || img.src}`).to.be.true;
        expect(
          img.naturalWidth,
          `naturalWidth: ${img.currentSrc || img.src}`
        ).to.be.greaterThan(0);
      }
    });

    cy.percySnapshot('Gallery - Images Loaded');
  });
});

The nonempty collection assertion is optional. Add it when an empty result would indicate that the page failed to render the expected gallery; omit it for pages where no images are valid. The descriptive assertion messages make a failure easier to diagnose.

3. Choose the right trigger and readiness condition

Scroll to the bottom or through the page?

cy.scrollTo('bottom') is concise and matches Percy’s example. It may not be sufficient when the application loads items only as they enter the viewport, or when loading the next batch requires an intermediate scroll. In those cases, move through the content in viewport-sized increments, allow the application’s event handlers to run, and assert that the expected content or images appear.

Viewport dimensions affect what the browser considers near the viewport. A responsive page can also render different image elements or use different sources at different widths. Keep the viewport consistent with the visual state you intend Percy to compare, and trigger loading at that size. Percy’s lazy-loading guide discusses viewport and network variation as reasons the exact wait depends on the implementation.

Limit the check to the relevant images

Checking every img is appropriate when the entire page’s image set should be ready. On a page with unrelated or intentionally broken images, select the gallery or component under test instead:

cy.get('[data-testid="product-gallery"] img').should(($imgs) => {
  for (const img of $imgs) {
    expect(img.complete).to.be.true;
    expect(img.naturalWidth).to.be.greaterThan(0);
  }
});

A stable test selector is preferable to a broad selector when the page contains icons, tracking pixels, or images outside the snapshot area. Choose a selector that represents the rendered feature, not a particular asset filename that may change.

Handle pages without ordinary image elements

The standard check does not cover an image painted as a CSS background-image, nor does it prove that a custom component has finished its own rendering work. For these cases, expose or assert a state that corresponds to the implementation—for example, a component’s loaded marker or the presence of its final rendered content. If the component uses an image request behind the scenes, wait on that component’s actual ready state rather than assuming document.images or img selectors cover it.

Also consider whether the test needs every image on a long page or only the images visible in the snapshot viewport. Full-page snapshots and viewport snapshots can have different relevant content and loading triggers. Define the intended capture area first, then make the readiness condition match it.

4. Avoid fixed sleeps as the primary wait

A test such as cy.wait(3000) waits three seconds whether images loaded in a fraction of a second or take longer than expected. Under variable network conditions, a delay that usually passes may still race the image load. It also adds avoidable runtime to faster runs.

Prefer the state-based assertion above. A targeted network wait can be useful when the application has a known request that reliably represents the image data, but a completed request does not always mean the browser has decoded and painted every image. The browser-level image condition is a better match when the requirement is that the selected img elements be ready for capture.

Other visual instability can remain after images load. Percy’s Cypress guidance recommends stabilizing animations, fonts, and network activity as well. Treat those as separate readiness conditions when they affect the comparison; passing the image assertion does not establish that every other part of the page is stable.

5. Tune timeouts and test reliability

If images load slowly in the test environment, increase the timeout for the relevant Cypress query or assertion according to the project’s existing timeout conventions. Keep the timeout attached to the specific readiness condition where possible, so unrelated commands do not inherit an unnecessarily long wait. A longer timeout gives a slow image more time; it does not repair an incorrect selector or a load trigger that never runs.

To reduce flaky results:

  • Set the viewport to the dimensions used by the visual test before triggering lazy loading.
  • Scroll in a way that exercises the application’s actual loading behavior.
  • Assert on the image elements included in the feature or capture.
  • Use both complete and positive naturalWidth for ordinary images.
  • Keep the snapshot command after all relevant state checks.
  • Stabilize fonts, animations, and relevant network activity independently when they affect the page.

These checks improve the signal but do not make an external image host reliable. If the host is unavailable, the image may fail consistently; the positive-width assertion should surface that failure instead of producing a misleading “ready” snapshot.

6. Troubleshooting common failures

Symptom Likely cause What to change
Snapshot has placeholders or blank images The lazy-loading trigger did not run, or the snapshot came before the request completed. Scroll through the relevant content, then place the readiness assertion before cy.percySnapshot().
Assertion times out on an image The request is slow, the image URL is broken, or the chosen selector includes an image that is not expected to load. Inspect the failing element’s src/currentSrc, narrow the selector if appropriate, and adjust the targeted timeout for expected slow loads.
complete is true but width is zero The image finished unsuccessfully or has no usable image data. Check the resolved URL and browser/network errors. Keep the positive-width assertion so the test reports the failure.
No images match the selector The page has not rendered the component, or the selector does not match its markup. Assert that the component is present first and use a selector tied to the actual page structure.
Images load only in a local run Viewport, network access, authentication, or test data differs in the visual run. Make viewport and data setup deterministic; verify that the test environment can reach the image host.
Some visual differences remain after images pass Fonts, animation, dynamic content, or other requests are still changing the page. Add separate stabilization steps for those states, following the project’s Percy setup.
CSS background remains blank The assertion only selects img elements. Wait for a readiness signal specific to the component or background-image implementation.

7. Performance and cost considerations

The state-based pattern adds only the time needed for the chosen images to become ready, whereas a fixed delay always consumes its full duration. Scrolling through a long page can cause more images and other content to load, so trigger only the area required by the snapshot. Tests that intentionally cover the full page should account for that broader work.

Visual test runtime also depends on the application, image host, network, and Percy workflow. The research sources provide no benchmark for this specific pattern, so there is no universal timeout or runtime saving to promise. Use the test’s observed behavior to choose a reasonable timeout and keep the readiness condition narrow enough to reflect the intended visual state.

Or skip the browser setup

If the goal is to obtain a website screenshot rather than validate a Cypress flow, ScreenshotNeo is a website screenshot API and MCP server. One GET request accepts a URL and returns a PNG, JPEG, WebP, or PDF. Its API options include full-page capture with lazy images loaded, viewport and device settings, custom waits, and element capture. See the API documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', new Uint8Array(await res.arrayBuffer()));

The Node.js example uses Bun’s file writer to save the response. In Node.js, use node:fs/promises instead:

import { writeFile } from 'node:fs/promises';

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
  • Cookie banners, popups, and chat widgets are removed before capture; each cleanup step can be turned off.
  • Bot checks, blank pages, and failed loads are never billed; response headers report the page verdict and billing status.
  • An MCP server lets AI agents, including Claude and Cursor, request screenshots.
  • The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Sign up free and get 1,000 screenshots a month with no card.

8. FAQ

Does img.complete mean the image loaded successfully?

No. Pair it with naturalWidth > 0 to reject images that completed without usable image data.

Should I wait for every image on the page?

Only when every image belongs to the visual state being tested. Otherwise, scope the selector to the relevant component.

Will this check CSS background images?

No. Define and assert a readiness condition that matches the component that renders the background.

Can I use a fixed timeout at all?

A delay can be useful for a known animation or other time-based behavior, but image readiness should generally be asserted from page state because load time varies.

Sources