jQuery API

.load()

.load( handler(eventObject) ) Returns: jQuery

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

  • version added: 1.0.load( handler(eventObject) )

    handler(eventObject)A function to execute when the event is triggered.

  • version added: 1.4.3.load( [eventData], handler(eventObject) )

    eventDataA map of data that will be passed to the event handler.

    handler(eventObject)A function to execute each time the event is triggered.

This method is a shortcut for .bind('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.

Examples:

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

$(window).load(function () {
  // run code
});

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

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

Support and Contributions

Need help with .load() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .load()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://www.egilder.org/ egilli

    Also works fine with iframes;

    $('iframe').load(function() {
    var iframeId = $(this).attr(“id”);
    var iframeHeight = $(this).contents().find(“body”).height();
    $(this).height(iframeHeight);
    });

  • http://twitter.com/mista_k Vladimir Kuznetsov

    Is it enough to just check the property «complete» to make sure that the image is loaded? Some times ago I read that Gecko-based browsers require to check the properties «naturalWidth» or «naturalHeight». They will be exactly equal to zero for not loaded yet images.

  • Chris

    dpn't know about Gecko, but at least in Opera .load() doesn't fire for images that allready lie in the browser's cache … writing something like

    $(“#myImg”).one(“load”,function(){
    //do something
    })
    .each(function(){
    if(this.complete) $(this).trigger(“load”);
    });

    seems to solve the problem.

  • http://profiles.yahoo.com/u/UN2NSPSUYPMHU7I7CYXDPXMNNA Derek B

    Load event wasn’t firing in IE or Firefox for me after caching. This solved it in those browsers as well for me. Perhaps we could get that snippet added to the doc up above as an example for catching images in cache.

  • http://www.ferretarmy.com/ Jon

    I currently have an iFrame that I wait for the ‘load’ event on. In IE8, this event isn’t firing after the framed page content is loaded (which happens when the page is loaded without the use of JavaScript). The ‘ready’ event is firing in IE, though, so I’ve got conditional code:

    if ($.browser.msie)
    $(‘#contentFrame’).ready(ParsePageData);
    else
    $(‘#contentFrame’).load(ParsePageData);

    Is there an issue with the load event for iframe elements in IE? In Firefox, the ‘ready’ event doesn’t work, so I have little recourse but to have the code above currently.

  • David

    I'd say that the following part is misguiding: “This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the body of the document itself.”

    With regards to the “– and the body –” part. Seeing as setting this to body immediately, will not work, while assigning it to window, as in the example above, will:

    http://jsbin.com/asizo/edit

  • Olaf

    Umm,
    Is it also possible to *REMOVE* such an event listener again?
    I am having the case where a library binds to load(..) on an image, however the corresponding function shall only be called once, not when the image.src is altered due to toggling….

  • Anonymous

    To get this code working on IE 6 I had to add one more condition to the If clause.

    $(“#myImg”).one(“load”,function(){
    //do something
    })
    .each(function(){
    if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
    $(this).trigger(“load”);
    });

  • http://www.learningjquery.com/ Karl Swedberg

    .unbind(‘load’) ?

  • Karazy

    I’m trying to display a message after a download in a hidden iFrame is complete.

    CODE:

    $(document.body).append(”);
    $(‘#pcl_frame’).attr(‘src’, ‘${printfile}’);
    $(‘#pcl_frame’).load(function()
    {
    if(‘${printfile}’ != ”)
    alert(‘IFRAME FINISHED LOADING’);
    });
    if($(‘#pcl_frame’).complete) $(‘#pcl_frame’).trigger(“load”);

    If src of iFrame is a website everything works as expected. But if src is a file to download load is never called. Is there a possibiity to get it work?

  • http://twitter.com/lenscraft Ron Lussier

    Is there any event that is triggered if an image load fails?

  • Gonzangus

    Yes there is, see this: http://api.jquery.com/error/

  • http://twitter.com/geoffmortimer Geoff Mortimer

    awesome, this.complete helps with cached loads perfectly (I had the issue in chrome and firefox – especially after navigating within the site)

  • Andrey

    if your PHP scripts are working with Windows-1251 encoding and you can not switch to utf-8
    You can save
    $ Str = htmlentities ('wqe23 rrYY Pearl hells sing Wash', ENT_NOQUOTES, 'Windows-1251');

    http://php.net/manual/en/function.htmlentities.php

  • Andry

    $str = htmlentities('Руские буквы' ,ENT_NOQUOTES, 'Windows-1251');

  • tyfuji

    Brilliant, thanks Stan and Chris. This solves non-firing .load and .each events for images in mozilla and webkit for me.

  • Tester testers

    I just want to mention that the event.special.load plugin for detecting image loads (linked at top of page) has problems in Firefox. See http://github.com/peol/jquery.imgloaded/issues

  • Chris

    I've just been testing an app that does a simple .load into a div and the .load doesn't work in firefox 4 beta 6, but it does work in 3.6.10, it's their issue, but hopefully not permanent

  • Arthur

    Problem with .load() in all versions of IE

    function hello(){
    alert('hello');
    }
    $('img').load(function(){
    hello();
    });

    Is it something that I'm doing wrong or is it IE?
    Everywhere else works fine.

  • Chenshao_jie

    $(window).load(function()); it's doesn't work in firefox….

  • Neotropic2012

    lol, yeah… pulling my hair out now over this as nothing works like it used to in FF4. Getting script code to run on dynamically loaded pages is a joke now. Try using $.get() I know that works still at least.

  • Pimus

    Corner Div when onload DIV width img



    <script language="JavaScript" src="jquery.corner.js"></script>

    function jqAjaxDivBox1Corner(a_targetid, a_tiempo)

    {

    setTimeout('$('+a_targetid+').corner('round 14px').parent().css('padding', '15px').corner('round 14px');', a_tiempo);

    }

    Then u need a div

    <div id="midiv" style=" border: 2px solid black;">

    <img onload="jqAjaxDivBox1Corner('$l_namebox1', 800);" src="images/miimg.gif">

    <div>

    When u load the page automatic cornered midiv</div></div>

  • Pimus

    [code]



    $l_namebox1 = midiv



    [/code]

  • Prashant M

    In chrome, the image load event is not fired if the existing src and the new src is same.

  • http://twitter.com/joemaffia Joe Maffia

    guys Im having a weird issue…

    all this solutions seems working for me only in webkit, both Firefox and IE always return 0 for the height of the iframe.

    any tip ?

  • John

    How do you get the [ eventData ] parameter to view it's contents? Also, is it possible to pass variables into the load event?

  • Henry Fai Hang Chan

    use $(obj).one('load', function)

  • Henry Fai Hang Chan

    use $(obj).one('load', function)

  • Jason

    I tried using the event.special.load plugin, and had some problems with it (it caused a stack overflow in IE). Commenting out the $(this).bind('load', hollaback.handler); line fixed this problem.

  • Codyjdalton

    Any suggestions on using this function for an Ajax loading image?

  • j_b_r

    The event.special.load plugin is causing “too much recursion” errors when I use bind('load') on images.

  • Ducain

    Brilliant – solve my issue of the day. Well done.

  • Fabrizio

    Thank you very much.. you saved me A LOT of time trying to figure out IE8 cached images issue

  • http://www.facebook.com/lawrencealan Larry Williamson

    If loading images dynamically via javascript,
    we can create the img element without a “src” attribute,
    and bind to load before setting the attribute.

    I have found this solution works best for me.

    ————-

    var _url = “image.jpg”;

    // set up the node / element
    _im =$(“<img>”);

    // hide and bind to the load event
    _im.hide();
    _im.bind(“load”,function(){ $(this).fadeIn(); });

    // append to target node / element
    $('body div#target').append(_im);

    // set the src attribute now, after insertion to the DOM
    _im.attr('src',_url);

    ————-

    Good luck!

  • Christian

    This worked for me as well… is it safe to comment this line out?