简体   繁体   English

加载图像后触发javascript的最快方法?

[英]Fastest way to fire javascript after an image has been loaded?

I have a portion of code that depends on knowing the width of an image on my page. 我有一部分代码依赖于知道页面上图像的宽度。

If I fire it immediately (at the top of $(function(){ it sometimes doesn't work, as the image hasn't loaded yet. 如果我立即将其触发(在$(function(){顶部$(function(){则有时不起作用,因为该图像尚未加载。

If I use jquery (I'm already using it for other stuff on the page) to fire on load(), it NEVER fires. 如果我使用jquery(我已经将它用于页面上的其他东西)在load()上触发,则永远不会触发。 Presumably because the image has loaded before the JS even executes, or because it's cached. 大概是因为图像在JS尚未执行之前就已加载,或者是由于已缓存。

$('#photo').load(function(){
    alert('loaded');
});
//doesn't fire

If I do the following, it does work, but after a noticeable delay while it fetches the image for the second time: 如果执行以下操作,则它确实可以工作,但是在第二次获取图像时出现了明显的延迟之后:

$('#photo').load(function(){
    alert('loaded');
});
$('#photo').attr('src',$('#photo').attr('src')+'?'+new Date().getTime());
//fires, but is slow

Surely in 2016 there must be a nice way of doing this? 当然在2016年一定有一种不错的方法吗? Either in jquery or vanilla JS. 无论是jquery还是vanilla JS。

Why not simply use onLoad function of the image: 为什么不简单使用图像的onLoad函数:

<img src="/path/to/image.jpg" onload="doStuff(this);" />

It will trigger once the image has loaded .. 图片载入后就会触发..

You could use the Unveil plugin to trigger a callback once your image has been loaded. 加载图像后,您可以使用Unveil插件触发回调。 As a bonus you'll also get lazyloading! 作为奖励,您还可以延迟加载!

$("img").unveil(200, function() {
  $(this).load(function() {
    // where you do your things... this = the image object
  });
});

I'm using the following: 我正在使用以下内容:

$('<img />').one('load', function() {
  // do stuff
}).attr('src', $('#photo').src);

Create a tag, attach a one time onload handler to it and only then tell it what the src url is. 创建一个标记,将一个onload处理程序附加到该标记,然后再告诉它src url是什么。

Another approach would be: 另一种方法是:

$('#photo').on("load",function(){
  // do stuff
}).each(function(){
  if(this.complete) {
    $(this).trigger('load');
  }
});

The idea here is that the chaining ensures that if the photo is in the cache and the onload handler is attached too late to catch it, the each(this.complete) section will save the day and fire the onload. 这里的想法是,链接可以确保如果照片在缓存中,并且onload处理程序的连接太晚而无法捕获,则each(this.complete)节将节省时间并触发onload。

Do these meet your definition of fast? 这些符合您对fast的定义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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