ScreenshotNeo

BlogHow-to

How to Make wkhtmltopdf Wait for jQuery’s Ready Event

Use jQuery, window.status, and wkhtmltopdf’s wait options to produce PDFs after AJAX, charts, images, and other asynchronous work finish.

By the ScreenshotNeo team30 September 20269 min read

How to Make wkhtmltopdf Wait for jQuery’s Ready Event

Direct answer: Put window.status = 'ready' at the end of the work that must finish, then invoke wkhtmltopdf with --window-status ready. jQuery’s ready callback tells you that the DOM exists; it does not automatically mean that AJAX requests, charts, lazy images, or other asynchronous rendering has completed.

<script>
$(function () {
  // Update the DOM, fetch data, draw charts, and replace placeholders here.
  window.status = 'ready';
});
</script>
wkhtmltopdf --window-status ready https://example.com/report.html report.pdf

The wkhtmltopdf usage documentation defines --window-status as waiting until window.status equals the supplied value. The same documentation describes --javascript-delay as a fixed wait; its default is 200 milliseconds. Use the status sentinel when completion is event-driven and use a delay only when you have a known, acceptable upper bound.

1. Why jQuery ready is not the same as finished rendering

jQuery’s $(function () {}) callback runs when the document hierarchy has been constructed. The browser can still be loading images, waiting for XHR or fetch responses, executing chart code, or replacing loading placeholders. jQuery’s documentation distinguishes DOM ready from the window load event, which waits for assets such as images: jQuery ready documentation.

For a PDF, define “finished” as the last state that must appear on paper. That might include:

  • Data returned by one or more AJAX requests.
  • Charts drawn onto a canvas or SVG.
  • Images loaded and inserted into the DOM.
  • Fonts applied and loading placeholders removed.
  • Totals, pagination, and other derived values calculated.

Set the sentinel only after those operations complete. Setting it as the first line of the ready callback merely proves that the DOM is available.

2. The reliable window.status pattern

Use a small state machine when your page has several asynchronous operations. The example below waits for an AJAX response and an image before allowing wkhtmltopdf to continue.

Signal wkhtmltopdf only after every asynchronous rendering step has completed.
Signal wkhtmltopdf only after every asynchronous rendering step has completed.
<!doctype html>
<html>
<head>
  <meta charset='utf-8'>
  <script src='https://code.jquery.com/jquery-3.7.1.min.js'></script>
</head>
<body>
  <div id='report'>Loading…</div>
  <img id='logo' src='/assets/logo.png' alt='Company logo'>

  <script>
  $(function () {
    var dataReady = $.getJSON('/api/report');
    var imageReady = new Promise(function (resolve, reject) {
      var image = document.getElementById('logo');
      if (image.complete) {
        resolve();
        return;
      }
      image.addEventListener('load', resolve);
      image.addEventListener('error', reject);
    });

    Promise.all([dataReady, imageReady])
      .then(function (results) {
        var data = results[0];
        $('#report').html(
          '<h1>' + $('
').text(data.title).html() + '</h1>' + '<p>Total: ' + $('
').text(data.total).html() + '</p>' ); // Draw charts or perform any final DOM updates here. window.status = 'ready'; }) .catch(function (error) { console.error('Report preparation failed', error); window.status = 'report-error'; }); }); </script> </body> </html>

Run it with a status value that matches the success path:

wkhtmltopdf --window-status ready https://example.com/report.html report.pdf

If the page can fail, do not leave wkhtmltopdf waiting forever. Set an error status and make the calling process detect it, or add an external process timeout. A status value is a browser-side signal; it is not a substitute for supervising the wkhtmltopdf process.

Use a unique sentinel

A value such as report-ready-v3 reduces accidental matches from unrelated scripts. The command and page must use exactly the same string, including capitalization.

Wait for all requests, not the first request

When several calls can finish in any order, aggregate them with Promise.all, jQuery’s $.when, or an equivalent counter. Assign the status in one final completion path so an early response cannot produce a partial PDF.

3. Fixed delays with –javascript-delay

A fixed delay is useful when you cannot modify the page or when the rendering time has a predictable upper bound:

wkhtmltopdf --javascript-delay 2000 https://example.com/report.html report.pdf

The library settings documentation describes load.jsdelay as the number of milliseconds to wait after page loading before printing, or until JavaScript calls window.print(): wkhtmltopdf page settings.

Approach Completion signal Strength Risk
--window-status ready Your code explicitly announces completion Works with variable AJAX and rendering times Can hang if the assignment is never reached; affected by some version-specific issues
--javascript-delay 2000 Elapsed time Works when you cannot change page code Too short creates incomplete output; too long wastes time and still does not prove completion
Both options Status plus delay May appear to add a safety margin Issue reports describe hangs or unexpected behavior in some builds; isolate options while diagnosing

Prefer the sentinel for production pages you control. Treat a delay as a timing estimate, not proof that asynchronous work has finished.

4. Options that affect JavaScript and loading

The wait flag controls when printing begins, but other options determine whether the page can reach the completion code.

  • --enable-javascript enables JavaScript. It is enabled by default in common builds, but specify it when your wrapper or configuration may disable scripts.
  • --javascript-delay <msec> adds a fixed post-load wait.
  • --debug-javascript prints JavaScript errors to stderr and is useful during diagnosis.
  • --no-stop-slow-scripts prevents wkhtmltopdf from stopping scripts it considers slow; use carefully because an actual infinite loop can then consume the process indefinitely.
  • --cookie name value, --custom-header name value, and related authentication options allow the page to load the same data as an authenticated browser.
  • --allow path permits access to local resources when your report uses local files. Review this setting closely when input is untrusted.

Keep the command minimal while establishing correctness. Add headers, cookies, local-file access, table of contents, or other features one at a time. The issue tracker contains reports of --window-status being ignored, commands hanging when it is combined with --javascript-delay, and behavior changing with argument ordering around toc. These reports are version and command dependent, so test the exact binary and invocation used in production.

5. A complete AJAX and chart example

This page waits for data, updates the DOM, draws a chart, waits for the chart image to finish loading, and then signals wkhtmltopdf.

<script src='https://code.jquery.com/jquery-3.7.1.min.js'></script>
<script>
$(function () {
  function drawChart(rows) {
    var canvas = document.getElementById('chart');
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    rows.forEach(function (row, index) {
      context.fillStyle = '#2864c7';
      context.fillRect(index * 40, canvas.height - row.value, 25, row.value);
    });
  }

  $.getJSON('/api/metrics')
    .then(function (payload) {
      $('#heading').text(payload.title);
      drawChart(payload.rows);
      return new Promise(function (resolve, reject) {
        var image = document.getElementById('supporting-image');
        if (image.complete) return resolve();
        image.onload = resolve;
        image.onerror = reject;
      });
    })
    .then(function () {
      document.documentElement.classList.add('render-complete');
      window.status = 'metrics-ready';
    })
    .catch(function (error) {
      console.error(error);
      window.status = 'metrics-error';
    });
});
</script>
wkhtmltopdf --enable-javascript --window-status metrics-ready --debug-javascript https://example.com/metrics.html metrics.pdf

Do not signal success from a timer that merely happens to run after the request. If network speed, server load, or data volume changes, that timer can become wrong.

6. Troubleshooting checklist

The PDF contains “Loading…”

  • Cause: the status assignment runs before AJAX or chart rendering.
  • Fix: move window.status into the final promise or AJAX completion handler. Confirm that the final DOM contains the expected values before assigning it.

wkhtmltopdf waits forever

  • Cause: JavaScript threw an exception, jQuery did not load, a request never completed, or the sentinel string is misspelled.
  • Fix: run with --debug-javascript, inspect stderr, verify the script order, and add an explicit error path. Reproduce with a minimal page that sets window.status = 'ready' from a short timer.

The ready callback never runs

  • Cause: jQuery failed to load because of a network, certificate, CSP, or local-file restriction.
  • Fix: check the exact URL, provide the required --cookie or --custom-header, host dependencies where appropriate, and inspect JavaScript diagnostics.

Images or fonts are missing

  • Cause: DOM ready occurred before assets loaded, or the asset host rejects wkhtmltopdf’s user agent.
  • Fix: wait for the relevant image load events, verify asset URLs from the conversion environment, and provide authentication headers or cookies if required.

The command behaves differently on another server

  • Cause: different wkhtmltopdf builds, operating systems, patched Qt versions, fonts, network policies, or command ordering.
  • Fix: capture wkhtmltopdf --version, operating-system details, the complete command, and a minimal HTML/CSS/JavaScript case. Compare binaries before changing application code.

--window-status appears ignored

Issue reports document this symptom in some builds. Remove unrelated options, especially toc and --javascript-delay, confirm the sentinel in a minimal file, and test the exact version. The official downloads page identifies the 0.12.6 series as stable and released June 11, 2020: wkhtmltopdf downloads.

7. Performance and reliability

Event-driven completion usually reduces wasted time because fast pages finish quickly while slow pages wait for their actual work. A fixed delay should be based on observed worst-case behavior, with a process-level timeout to prevent stuck conversions. Reuse a warmed application environment only if it does not leak cookies or page state between jobs.

For repeatable output:

  • Pin the wkhtmltopdf version and record it with each deployment.
  • Use deterministic data and stable asset URLs.
  • Set explicit dimensions, fonts, and print CSS.
  • Log the URL, command options, exit code, stderr, duration, and output size.
  • Keep a minimal regression page that tests jQuery, AJAX, images, and the sentinel.
  • Apply an external timeout and terminate the child process if it exceeds your limit.

Be careful with untrusted HTML. The project warns that unsanitized HTML and JavaScript can enable complete server takeover. Treat HTML sources, local-file access, outbound network access, and process isolation as deployment concerns. Never pass arbitrary user content to a privileged conversion process without sanitization and sandboxing.

8. When to choose another renderer

wkhtmltopdf depends on the WebKit1 in-process API. Its status page recommends Puppeteer for sites using dynamic JavaScript and WeasyPrint or the commercial Prince engine for controlled report generation: wkhtmltopdf status.

Consider Puppeteer when the page depends on modern browser APIs, complex client-side frameworks, service workers, or reliable network-idle and selector waits. Consider WeasyPrint or Prince when your input is controlled HTML/CSS and print layout matters more than browser JavaScript. Keep wkhtmltopdf when its rendering engine matches your existing documents and the status-sentinel pattern produces stable output.

9. Or skip the browser setup

If your goal is a clean screenshot or PDF rather than maintaining a wkhtmltopdf runtime, ScreenshotNeo provides a website screenshot API and MCP server. The API accepts one GET request and returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for the complete option list.

ScreenshotNeo can remove common consent banners, popups, and chat widgets before capture.
ScreenshotNeo can remove common consent banners, popups, and chat widgets before capture.
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}`);

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its options include full-page capture with lazy images loaded, CSS selector element capture, dark mode, device presets and custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, click and wait actions, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification.

An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try the API.

10. FAQ

Can I set window.status directly inside $(document).ready()?

Yes, but only when all required work has already completed. For AJAX, charts, and images, assign it from the final completion handler.

Does window.status wait for network idle?

No. It waits for the exact string you configure. Your page must define what completion means and assign the value at that point.

Should I use ready or load?

Use ready for DOM setup and add explicit waits for the assets and asynchronous work that affect the PDF. The load event alone does not cover later AJAX rendering.

Is a two-second delay reliable?

Only if two seconds exceeds the real completion time in every supported environment. Variable network and server times make event signaling safer.

What should I include in a bug report?

Include the wkhtmltopdf version, operating system and version, complete command, stderr, minimal HTML/CSS/JavaScript, and whether removing options changes the result.