Javascript

How can I run a JavaScript callback when an image is loaded

27 September 2026 · 7 min read

How can I run a JavaScript callback when an image is loaded

In the dynamic world of web development, images are often the largest and most critical assets on a page. Ensuring they load efficiently and trigger specific actions at the right moment is crucial for a smooth user experience. Developers frequently ask: How can I run a JavaScript callback when an image is loaded? This seemingly simple task involves understanding various browser events and modern JavaScript features to implement robust and performant solutions. Whether you’re preloading assets, displaying a loading spinner, or performing post-load manipulations, correctly attaching a callback to an image’s load state is fundamental. This guide will delve into the traditional event listener approach, explore modern Promise-based solutions, and cover best practices for optimizing image loading in your applications.

Understanding Image Loading Events in JavaScript

At its core, running a JavaScript callback when an image is loaded relies on the browser’s native event system. Images, like many other HTML elements, emit events as their loading lifecycle progresses. The two primary events you’ll interact with are onload and onerror. These events provide crucial hooks to execute functions based on whether an image successfully loads or encounters an issue.

The ability to precisely control actions upon image loading is vital for front-end performance and user experience. For instance, you might want to fade in an image once it’s fully rendered, or perhaps hide a placeholder element. Understanding these event types is the first step towards mastering image loading in JavaScript applications, ensuring your content appears seamlessly and responsively.

The onload Event

The onload event fires when an object has been completely loaded. For an <img> element, this means the image data has been fully downloaded and decoded by the browser, making it ready for display. It’s the most common event used for attaching callbacks to successful image loads. When you attach a function to this event, that function will execute only after the image is entirely ready, preventing layout shifts or visual glitches that can occur if you try to manipulate an image before it’s fully available.

Using onload is straightforward and provides a reliable way to trigger actions like resizing images based on their intrinsic dimensions, or removing a loading indicator. This event is supported across all modern browsers and remains a cornerstone for responsive web design. According to a study by Google, optimizing image loading can significantly improve Core Web Vitals, directly impacting user satisfaction and SEO rankings. Read more about optimizing Largest Contentful Paint (LCP).

The onerror Event

While onload handles success, the onerror event is equally important for handling failures. This event fires if an error occurs during the loading of an object, such as a broken image URL, network issues, or unsupported image formats. Attaching a callback to onerror allows you to implement robust error handling, like displaying a fallback image, showing an error message to the user, or logging the issue for debugging purposes.

Effective error handling prevents broken images from disrupting the user interface and provides a more resilient application. For example, if a user’s network connection is unstable, gracefully handling image load failures can prevent a poor user experience. It’s essential to pair onload with onerror to cover all possible scenarios when dealing with external image resources.

Traditional Approach: Using Event Listeners

The most direct and widely compatible method for running a JavaScript callback when an image is loaded is by using event listeners. This approach can be applied directly to an existing <img> element in your HTML or to an Image object created programmatically in JavaScript. Both methods leverage the same onload and onerror events, but their implementation details differ slightly based on how the image element is managed.

This traditional method is reliable and provides fine-grained control over individual image loading states. It’s particularly useful when you have a specific image that needs a unique action upon loading or error. Many legacy and existing codebases rely heavily on this pattern due to its simplicity and robust browser support.

Direct <img> Element

If your <img> tag is already present in the HTML, you can select it using standard DOM manipulation methods and then attach event listeners. The callback function will then execute once the browser finishes loading the image associated with that specific element.

<img id="myImage" src="path/to/your/image.jpg" alt="Description"> <script> const myImage = document.getElementById('myImage'); myImage.onload = function() { console.log('Image loaded successfully!'); // Perform actions after image loads, e.g., show image, hide spinner myImage.style.opacity = 1; // Example: Fade in }; myImage.onerror = function() { console.error('Error loading image!'); // Handle error, e.g., replace with a fallback image myImage.src = 'path/to/fallback/image.png'; }; </script> 

It’s important to note that if the image is already in the browser cache when the script runs, the onload event might not fire consistently or immediately. To mitigate this, developers often set the src attribute after attaching the listeners, especially for dynamically loaded images. This ensures the browser re-evaluates the image source after the listeners are in place.

Programmatic Image() Object

For images that are not initially in the DOM, or for preloading purposes, you can create an Image object programmatically using JavaScript. This method is excellent for preloading images that might be needed later, like gallery images, without displaying them immediately. It allows you to load images in the background and only insert them into the DOM once they are fully ready.

<script> const img = new Image(); img.onload = function() { console.log('Programmatic image loaded!'); // Append the image to the DOM once loaded document.body.appendChild(img); // You can also access its dimensions here: img.naturalWidth, img.naturalHeight }; img.onerror = function() { console.error('Programmatic image failed to load!'); // Handle failure for this background load }; // Set the src AFTER attaching the listeners img.src = 'path/to/another/image.jpg'; </script> 

This technique is particularly useful for implementing lazy loading or image preloading strategies, where you want to defer loading until images are needed or ensure they are available before a user navigates to them. When you want to run a JavaScript callback when an image is loaded, this programmatic approach offers flexibility and control over the loading process, separating the loading logic from the rendering logic.

  • Always attach onload and onerror listeners before setting the src attribute to ensure events fire reliably.
  • For images already in the DOM, consider checking myImage.complete property if you need to handle cached images.
  • Use descriptive callback functions to improve code readability and maintainability.

Modern JavaScript: Leveraging Promises and Async/Await

While event listeners are effective, dealing with multiple images or complex loading sequences can lead to “callback hell” or harder-to-read asynchronous code. Modern JavaScript, with its Promises and async/await syntax, provides a more elegant and readable way to manage asynchronous operations like image loading. This approach allows you to treat image loading as an operation that can either “resolve” (load successfully) or “reject” (fail to load), fitting perfectly into the Promise pattern.

Using Promises for image loading not only cleans up your code but also makes it easier to chain operations, handle errors centrally, and manage concurrent image loads. This paradigm shift makes it much simpler to run a JavaScript callback when an image is loaded, especially when coordinating multiple image assets or integrating with other asynchronous tasks within your application flow.

Building a Promise-Based Loader

We can wrap the traditional Image object creation and its event listeners inside a Promise. This creates a reusable function that returns a Promise, Question & Answer :

I want to know when an image has finished loading. Is there a way to do it with a callback?

If not, is there a way to do it at all?

.complete + callback

This is a standards compliant method without extra dependencies, and waits no longer than necessary:

var img = document.querySelector('img') function loaded() { alert('loaded') } if (img.complete) { loaded() } else { img.addEventListener('load', loaded) img.addEventListener('error', function() { alert('error') }) } 

Source: http://www.html5rocks.com/en/tutorials/es6/promises/