如果图像已经加载,则jQuery.load()回退
jQuery .load() fallback if image is already loaded
Im使用jQuery load()函数绑定到图像的onload事件,以轻轻地将它们转换进来。
问题是,如果在调用image.load()函数之前已经加载了映像,则回调函数永远不会触发。
在我调用load()之前,有没有一种方法可以检测图像是否已经加载?
原因是它是一个提线木偶应用程序,在视图之间移动图像会被缓存,并且可能在调用渲染函数之前就已经加载了。
基本上我的代码在哪里:
preloadImages: function () {
var images = $('.grid .item > img');
var initialHeight = images.eq(0).width();
images.each(function(){
$(this).height(initialHeight).css("opacity", 0);
$(this).load(function(){
$(this).css("height", "").animate({"opacity": 1}, 200);
})
});
}
在我调用load()之前,有没有一种方法可以检测图像是否已经加载?
是的。img
元素具有complete
标志,因此:
images.each(function() {
var $this = $(this);
$this.on("load", handleLoad);
if (this.complete) { // `this` = the DOM element
$this.off("load", handleLoad);
handleLoad.call(this);
}
});
(请注意,这是简化的,我省略了测量第一个img
的代码—除非CSS强制使用特定宽度—并且使用handleLoad
而不是内联函数,否则您需要等待加载,直到加载。)
注意事物的顺序:
首先,挂接
load
事件。然后检查
complete
。如果
complete
为true,则取消挂起load
并直接调用处理程序。
为什么要这样做?因为即使主JavaScript UI线程只有一个线程,浏览器也不是单线程的。因此,如果您执行了if (!this.complete) { $(this).on("load", handleLoad); }
,那么代码看到complete
没有设置是完全有效的,然后在您可以将加载事件挂接到下一行之前,浏览器会触发load
事件;由于浏览器当时检查了已注册事件处理程序的列表,但没有找到任何事件处理程序,因此不会对任何事件回调进行排队。这不太可能,但有效。
另一种方法是使用jQuery的one
函数,该函数注册一个在第一次调用时注销自身的处理程序:
images.each(function() {
var $this = $(this);
$this.one("load.myload", handleLoad);
if (this.complete) { // `this` = the DOM element
$this.trigger("load.myload");
}
});
注意名称空间(.myload
)。您不希望激发其他可能已经激发或排队的load
处理程序。
- jQuery点击ON现在使用.load触发关闭
- 使用jquery.load('pageName')方法时,未从应用程序缓存加载Html页
- jQuery css可见性在load方法中不起作用
- 动态潜水高度jQuery.Load()不工作
- jQuery .load with variable as url
- jQuery.load()是另一个包含prism.js的页面
- jQuery and YUI load
- 使用.load()-jQuery缓慢加载内容
- for循环中的jquery.load()不起作用
- jQuery load()回调导致POST而不是GET
- css动画和jquery.load()在移动设备上断断续续
- jquery load()没有加载内容
- 在.load jquery中使用JSON返回的页面url
- 花哨的框回调函数 .load jquery
- 如何使用.load jQuery获取响应
- 函数内部页面使用load() jquery后不能正常工作
- 使用.load jquery时执行c#代码
- Load jQuery with RequireJS
- 是否有一种方法来加载一个函数从htm,你重新加载与.load()?JQuery
- 通过$.load jquery发送和获取数据