简体   繁体   中英

Execute code after all images are loaded

I want to do some interface fixes after all images are loaded (need the heights of the elements that hold images and use them to change the heights of other elements) I attach load event to all images but my load function is executed only once. I've try to use only jQuery:

$(function() {
    var $img = $('img');
    var length = $img.length;
    var count = 0;

    function load() {
       console.log(++count + ' == ' + length);
       if (count == length) {
          // all images loaded
       }
    }
    $img.load(load).error(load);
});

I also try to use onload and onerror events:

$img.each(function() {
    this.onload = load;
    this.onerror = load;
});

but when page is loaded I've got just one log:

1 == 33

(I'm testing in Chromium on Xubuntu with Dev Tools and cache disabled)

What I've doing wrong here? How to execute code after all images are loaded?

Sounds like you should be handling on the window 's load event:

$( window ).load(function() {
// Glorious code!!
}

From the docs: "Run a function when the page is fully loaded including graphics."

http://api.jquery.com/load-event/

Execute the function when the page has finished loading

$(window).load

That way all elements are in place and ready to be 'measured'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM