Free tools Windows power users keep installed

One-click scans. No signup required.

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

The correct callback depends on what you mean by “image.” For an interactive Plotly chart, chain code to the promise returned by Plotly.newPlot(). To run code after every plotting pass, listen for plotly_afterplot. For a static export, await Plotly.toImage(); that promise means Plotly has generated the image data URL, not necessarily that the browser has finished decoding an <img>.

Choose the completion signal first

What must be complete? Use Meaning
Initial interactive chart render Plotly.newPlot(...).then(...) The initial plot call has completed.
Every chart plotting pass plotly_afterplot The graph has been plotted again, including after updates such as restyle or relayout.
Plotly-generated static image Plotly.toImage(...) Plotly has produced an image data URL.

These are different lifecycle points. A chart rendered into a graph div is not the same thing as an exported image, and an exported data URL is not the same thing as the browser decoding an <img>. Plotly’s official documentation covers the first two signals and the export promise: event handlers, the function reference, and static image export.

Run code once after the initial Plotly render

Use the promise returned by Plotly.newPlot when your code should run once after the initial chart has been plotted.

const data = [
  {
    x: ['Jan', 'Feb', 'Mar'],
    y: [12, 19, 15],
    type: 'bar'
  }
];

const layout = { title: 'Quarterly example' };

Plotly.newPlot('myDiv', data, layout)
  .then((gd) => {
    // The initial interactive chart render has completed.
    runMyCode(gd);
  })
  .catch((error) => {
    console.error('Plotly failed to render:', error);
  });

function runMyCode(graphDiv) {
  graphDiv.classList.add('chart-ready');
  console.log('Ready:', graphDiv); 
}

The resolved value is the graph div (gd). Keeping that reference is useful when the same page contains several charts. A promise callback also lets you handle a rendering failure instead of silently running code too early.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Use a graph-div reference

You can pass the DOM element rather than its ID. This avoids looking it up again in the callback:

const gd = document.getElementById('myDiv');

Plotly.newPlot(gd, data, layout).then(() => {
  gd.setAttribute('aria-busy', 'false');
});

Set any loading state before calling newPlot, then clear it in the promise handler. Do not substitute an arbitrary setTimeout; a timer is only a guess and can fire before a slow plot has completed.

Run code after every plotting pass

If your handler must run again after Plotly.react, Plotly.restyle, Plotly.relayout, or another operation causes the chart to be plotted, attach a plotly_afterplot listener to the graph div.

const gd = document.getElementById('myDiv');

gd.on('plotly_afterplot', () => {
  runAfterEveryPlot(gd);
});

// Attach the listener before this call so it also catches the initial pass.
Plotly.newPlot(gd, data, layout);

function runAfterEveryPlot(graphDiv) {
  console.log('A plotting pass completed');
  document.querySelector('#status').textContent = 'Chart ready';
}

Plotly documents plotly_afterplot as an event triggered each time a chart is plotted. Because it can recur, make the handler idempotent: update existing UI, rather than appending duplicate controls or registering duplicate listeners on every event.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Prevent duplicate work

let lastRevision = 0;

 gd.on('plotly_afterplot', () => {
  const revision = gd.layout?.datarevision;
  if (revision === lastRevision) return;
  lastRevision = revision;
  updateOverlay(gd);
});

Only add a guard when your application has a reliable revision value. In many cases, simply making updateOverlay replace its output is safer than trying to infer whether a plot changed.

Wait for a static image generated by Plotly

For a PNG, JPEG, WebP, or other export created from a chart, first await the plot and then await Plotly.toImage. The export promise resolves with a data URL.

async function createExport() {
  const gd = await Plotly.newPlot('myDiv', data, layout);

  const imageUrl = await Plotly.toImage(gd, {
    format: 'png',
    width: 800,
    height: 600
  });

  const img = document.getElementById('exportedImage');
  img.src = imageUrl;

  // Plotly has generated the URL and it has been assigned to the image.
  afterExportGenerated(imageUrl);
}

createExport().catch((error) => {
  console.error('Could not create export:', error);
});

This follows Plotly’s documented export flow. The toImage promise tells you that Plotly produced the image data URL. The official pages do not define that promise as a guarantee that the browser has completed a later image-display or decode milestone.

If you need the browser’s image decode milestone

After assigning src, use the browser’s image API when your next operation requires decoded pixels. img.decode() returns a promise in browsers that support it; an onload handler is the broadly compatible fallback.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
async function putExportInPage() {
  const gd = await Plotly.newPlot('myDiv', data, layout);
  const imageUrl = await Plotly.toImage(gd, { format: 'png', width: 800, height: 600 });
  const img = document.getElementById('exportedImage');
  img.src = imageUrl;

  if (img.decode) {
    await img.decode();
  } else if (!img.complete) {
    await new Promise((resolve, reject) => {
      img.onload = resolve;
      img.onerror = reject;
    });
  }

  // The browser has completed the decode step (where supported).
  afterBrowserDecode(img);
}

This browser-level step is separate from Plotly’s documented export lifecycle. If the image is already cached, complete may be true immediately; check the element’s state before installing a listener.

Complete examples for common application patterns

Disable a loading indicator

const gd = document.getElementById('myDiv');
const spinner = document.getElementById('spinner');

gd.on('plotly_afterplot', () => {
  spinner.hidden = true;
});

Plotly.newPlot(gd, data, layout).catch(() => {
  spinner.textContent = 'Chart could not be loaded';
});

Run once, then react to updates

const gd = document.getElementById('myDiv');
let initialized = false;

gd.on('plotly_afterplot', () => {
  if (!initialized) {
    initialized = true;
    initializeChartControls(gd);
  }
  refreshChartDependentUi(gd);
});

await Plotly.newPlot(gd, data, layout);
await Plotly.restyle(gd, { y: [[20, 14, 18]] });

The listener catches both the initial pass and the later restyle. Use Plotly.newPlot(...).then(...) instead when controls must be initialized only once and do not need to observe future plotting.

Failure modes and fixes

The callback never runs

  • Check that the Plotly script loaded before your code and that Plotly exists.
  • Verify that myDiv is present and is the graph div, not a wrapper around it.
  • Attach plotly_afterplot before Plotly.newPlot; attaching afterward can miss the initial event.
  • Always add a .catch to the promise so a rendering error is visible.

The handler runs more than once

That is expected for plotly_afterplot. It is an every-pass event, including update-driven plotting. Make the handler idempotent, use a one-time initialization flag, or switch to the newPlot promise for initial-only work.

The image is blank or has the wrong size

  • Provide explicit width and height to Plotly.toImage when the layout’s responsive size is not established.
  • Await newPlot before calling toImage.
  • Inspect the rejected promise; export can fail if the chart or its dependencies did not render correctly.

Code runs before an image appears

Decide which milestone you need. The toImage promise covers export generation. Assign its URL to img.src, then await img.decode() or handle onload if you need browser decoding. Neither a timer nor the plot event alone proves that a separate <img> element has decoded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Updates trigger expensive work repeatedly

Keep the event handler small, debounce application work if updates arrive in bursts, and avoid calling another plotting method from the handler unless you intentionally need a second pass. A handler that mutates the chart on every plotly_afterplot can create a feedback loop.

Performance and reliability considerations

  • Prefer promise chaining for a single known operation; it avoids an always-on listener.
  • Prefer plotly_afterplot when several code paths can replot the same graph and all must notify the UI.
  • Register listeners once, especially in component frameworks where mounting can happen repeatedly. Remove them with your framework’s cleanup mechanism when the graph is destroyed.
  • Do not treat a successful callback as proof that remote data requests, fonts, or unrelated page images have finished. It signals Plotly’s documented plot or export milestone.
  • Handle rejection and event-handler exceptions separately so a UI update failure does not hide the original rendering error.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean screenshot or PDF of the finished page rather than code running inside Plotly, ScreenshotNeo provides a one-request capture API. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing result. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

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 documentation for all options, including full-page lazy-image loading, CSS-selector element capture, device and viewport settings, retina scale, PDF controls, custom JavaScript and CSS, click and wait conditions, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture, usage data, and the OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration.

Equivalent Python request

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Equivalent Node.js request

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 failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('shot.webp', image);

Every feature is included on every plan: 1,000 screenshots per month are free with no card; paid plans start at $5 for 3,000 shots. Yearly billing provides two months free. Create a free ScreenshotNeo account.

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

Which approach should you use?

  • Use Plotly.newPlot(...).then(...) for one action after the initial interactive render.
  • Use plotly_afterplot for an action after every plotting pass.
  • Use Plotly.toImage(...) for the completion of Plotly’s static export generation.
  • Use img.decode() or onload after assigning the export URL when browser image decoding is the actual requirement.

Frequently Asked Questions

Does Plotly have an image-load event for a chart in a div?

For an interactive chart, use the promise from Plotly.newPlot or the plotly_afterplot event; an HTML image-load event applies to an img element, not the graph div.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Can I use plotly_afterplot only for the first render?

It can fire on later plotting passes too. Add a one-time flag in the handler or use the newPlot promise for initial-only code.

Does Plotly.toImage wait for the browser to display the image?

No documented guarantee covers that later display milestone. It resolves when Plotly has generated the image data URL; await img.decode or use onload after assigning src if decoding matters.

The Bottom Line

Match the callback to the milestone: newPlot for the initial chart, plotly_afterplot for every plot, and toImage for export generation.

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.