How to call function after document ready AND image load?

删除回忆录丶 提交于 2020-01-13 09:36:46

问题


I was using something like this:

$(document).ready(function() {
  $('#my-img').load(function() {
    // do something
  });
});

But sometimes it fails to execute the second callback (without throwing any errors, so there's nothing to do there), and I'm thinking that maybe the image is being loaded before the document is ready.

If I don't use the $(document).ready() part, it works fine, so I think I'm gonna leave it that way for now. But someone told me that it was a good practice to always do this kind of thing as a callback on document ready, because the document might not be ready. Is that right?

Any thoughts?


回答1:


Taken from the documentation on load()

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****

Especially the latter is a common problem.

You might try the imagesLoaded plugin, but I've had better luck with the following approach:

var element = $('#my-img');
$("<img/>").load(function () { //create in memory image, and bind the load event
    //do something
    //var imageHeight = this.height;
}).attr("src", element.attr("src"));
//set the src of the in memory copy after binding the load event, to avoid WebKit issues

It's dirty, but if you really need to perform some action after the image has loaded this has been the only reliable approach I've been able to get to work.




回答2:


Old question but may be useful to googlers: If you need code to execute after images are loaded, and the images are in the DOM, you should use $(window).load instead of $(document).ready. As in:

$(window).load(function() {
    console.log("My image is " + $('#my-img').width() + " pixels wide.");
    // You may not have known this before the image had loaded
});

This is vital if doing any jiggerypokery with SVGs or other embedded documents.



来源:https://stackoverflow.com/questions/7381603/how-to-call-function-after-document-ready-and-image-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!