javascript – 如何在文档准备好和图像加载后调用函数?

前端之家收集整理的这篇文章主要介绍了javascript – 如何在文档准备好和图像加载后调用函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用的是这样的东西:
$(document).ready(function() {
  $('#my-img').load(function() {
    // do something
  });
});

但有时它无法执行第二次回调(没有抛出任何错误,所以没有什么可做的),我想也许图像是在文档准备好之前加载的.

如果我不使用$(document).ready()部分,它工作正常,所以我想我现在就要离开它了.但是有人告诉我,总是做这样的事情作为文件准备回调是一个好习惯,因为文档可能还没准备好.是对的吗?

有什么想法吗?

解决方法

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

特别是后者是一个常见问题.

您可以试试imagesLoaded plugin,但我有更好的运气,采用以下方法

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

它很脏,但如果你真的需要在图像加载后执行一些动作,这是我能够开始工作的唯一可靠方法.

原文链接:https://www.f2er.com/js/154517.html

猜你在找的JavaScript相关文章