.load()

Bind an event handler to the "load" JavaScript event.

.load(function(eventObjectEvent))🡢 jQuery

function(eventObjectEvent) FunctionA function to execute when the event is triggered.

.load(eventData, function(eventObjectEvent))🡢 jQuery

eventData AnythingAn object containing data that will be passed to the event handler.
function(eventObjectEvent) FunctionA function to execute each time the event is triggered.

Note: This API has been removed in jQuery 3.0; please use .on( "load", handler ) instead of .load( handler ) and .trigger( "load" ) instead of .load().

This method is a shortcut for .on( "load", handler ).

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

For example, consider a page with a simple image:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

$("#book").load(function () {
  // Handler for .load() called.
});

As soon as the image has been loaded, the handler is called.

In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.

The Ajax module also has a method named .load(). Which one is fired depends on the set of arguments passed.

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

Note: The .live() and .delegate() methods cannot be used to detect the load event of an iframe. The load event does not correctly bubble up the parent document and the event.target isn't set by Firefox, IE9 or Chrome, which is required to do event delegation.

Run a function when the page is fully loaded including graphics.

HTML
$(window).load(function () {
  // Run code
});
DEMO

Add the class bigImg to all images with height greater than 100 upon each image load.

HTML
$("img.userIcon").load(function () {
  if ($(this).height() > 100) {
    $(this).addClass("bigImg");
  }
});
DEMO

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)