我怎样才能确定如果图像已经加载,使用Javascript / jQuery?

我正在写一些JavaScript来调整大的图像,以适应用户的浏览器窗口。 (我不能控制源图像的大小。)

所以像这样的东西会在HTML中:

<img id="photo" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /> 

有没有一种方法可以确定是否已经下载了img标签中的src图像?

我需要这个,因为如果在浏览器加载图像之前执行$(document).ready()我会遇到问题。 $("#photo").width()$("#photo").height()将返回占位符(alt文本)的大小。 在我的情况下,这是像134×20。

现在我只是检查照片的高度是否小于150,并假设如果是这样,它只是文字。 但是,这是一个相当黑客,如果一张照片小于150像素(不可能在我的具体情况下),或者如果alt文本高于150像素(可能发生在一个小的浏览器窗口) 。


编辑:任何人想看到的代码:

 $(function() { var REAL_WIDTH = $("#photo").width(); var REAL_HEIGHT = $("#photo").height(); $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(REAL_HEIGHT < 150) { REAL_WIDTH = $("#photo").width(); REAL_HEIGHT = $("#photo").height(); if(REAL_HEIGHT < 150) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } } var new_width = . . . ; var new_height = . . . ; $("#photo").width(Math.round(new_width)); $("#photo").height(Math.round(new_height)); } }); 

更新 :感谢您的build议。 如果我为$("#photo").load事件设置了callback,就有可能不会触发事件,所以我直接在image标签中定义了一个onLoad事件。 为了logging,这里是我最终的代码:

 <img id="photo" onload="photoLoaded();" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /> 

然后在Javascript中:

 //This must be outside $() because it may get called first var isPhotoLoaded = false; function photoLoaded() { isPhotoLoaded = true; } $(function() { //Hides scrollbars, so we can resize properly. Set with JS instead of // CSS so that page doesn't break with JS disabled. $("body").css("overflow", "hidden"); var REAL_WIDTH = -1; var REAL_HEIGHT = -1; $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(!isPhotoLoaded) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } else if(REAL_WIDTH < 0) { //first time in this function since photo loaded REAL_WIDTH = $("#photo").width(); REAL_HEIGHT = $("#photo").height(); } var new_width = . . . ; var new_height = . . . ; $("#photo").width(Math.round(new_width)); $("#photo").height(Math.round(new_height)); } }); 

可以添加一个事件监听器,也可以使用onload来宣告自己的图像。 然后从那里算出尺寸。

 <img id="photo" onload='loaded(this.id)' src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /> 

使用jQuery数据存储,你可以定义一个“加载”状态。

 <img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" /> 

然后在别处你可以做:

 if ($('#myimage').data('loaded')) { // loaded, so do stuff } 

正确的答案是使用event.special.load

如果图像是从浏览器caching中加载的,则可能不会触发加载事件。 考虑到这种可能性,我们可以使用一个特殊的加载事件,如果图像准备就绪,立即触发。 event.special.load当前可用作插件。

根据.load()的文档

你想要做Allain所说的,不过要注意的是,有时候图像会在dom准备好之前加载,这意味着你的载入处理程序不会触发。 最好的办法就是像Allain所说的那样做,但是在附加了加载器之后用javascript来设置图像的src。 这样你可以保证它会被触发。

在可访问性方面,您的网站仍然为没有javascript的人工作? 你可能要给img标签正确的s​​rc,附上你准备好的处理程序来运行你的js:清除图像的src(给它一个固定的高度与css以防止页面闪烁),然后设置你的IMG负载处理程序,然后将src重置为正确的文件。 这样你覆盖所有的基地:)

根据你最初的问题最近的评论之一

 $(function() { $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if (!$("#photo").get(0).complete) { $("#photo").load(function() { adjust_photo_size(); }); } else { ... } }); 

警告这个答案可能导致严重的ie8和更低的循环,因为img.complete并不总是由浏览器正确设置。 如果您必须支持ie8,请使用标记来记住图像已加载。

尝试像这样:

 $("#photo").load(function() { alert("Hello from Image"); }); 

对此有何评论?

 doShow = function(){ if($('#img_id').attr('complete')){ alert('Image is loaded!'); } else { window.setTimeout('doShow()',100); } }; $('#img_id').attr('src','image.jpg'); doShow(); 

似乎无处不在…

有一个叫做“imagesLoaded”的jQuery插件,它提供了一个跨浏览器兼容的方法来检查一个元素的图像是否已经被加载。

网站: https : //github.com/desandro/imagesloaded/

用于内部有许多图像的容器:

 $('container').imagesLoaded(function(){ console.log("I loaded!"); }) 

该插件是伟大的:

  1. 用于检查里面有很多图像的容器
  2. 作品检查IMG,看看是否已经加载

我刚刚创build了一个jQuery函数来使用jQuerys Deferred Object加载图像,这使得在加载/错误事件中很容易做出反应:

 $.fn.extend({ loadImg: function(url, timeout) { // init deferred object var defer = $.Deferred(), $img = this, img = $img.get(0), timer = null; // define load and error events BEFORE setting the src // otherwise IE might fire the event before listening to it $img.load(function(e) { var that = this; // defer this check in order to let IE catch the right image size window.setTimeout(function() { // make sure the width and height are > 0 ((that.width > 0 && that.height > 0) ? defer.resolveWith : defer.rejectWith)($img); }, 1); }).error(function(e) { defer.rejectWith($img); }); // start loading the image img.src = url; // check if it's already in the cache if (img.complete) { defer.resolveWith($img); } else if (0 !== timeout) { // add a timeout, by default 15 seconds timer = window.setTimeout(function() { defer.rejectWith($img); }, timeout || 15000); } // return the promise of the deferred object return defer.promise().always(function() { // stop the timeout timer window.clearTimeout(timer); timer = null; // unbind the load and error event this.off("load error"); }); } }); 

用法:

 var image = $('<img />').loadImg('http://www.google.com/intl/en_comhttp://img.dovov.comsrpr/logo3w.png') .done(function() { alert('image loaded'); $('body').append(this); }).fail(function(){ alert('image failed'); }); 

看到它的工作: http : //jsfiddle.net/roberkules/AdWZj/

此function会根据可测量的尺寸检查图像是否已加载。 如果您的脚本在一些图像已经被加载之后执行,这种技术是有用的。

 imageLoaded = function(node) { var w = 'undefined' != typeof node.clientWidth ? node.clientWidth : node.offsetWidth; var h = 'undefined' != typeof node.clientHeight ? node.clientHeight : node.offsetHeight; return w+h > 0 ? true : false; }; 

我发现这对我有用

 document.querySelector("img").addEventListener("load", function() { alert('onload!'); }); 

诚然,弗兰克·施维特曼(Frank Schwieterman)评论了接受的答案。 我不得不把这个放在这里,太贵了…

我们开发了一个页面,它载入了许多图像,然后在图像加载之后才执行其他function。 这是一个繁忙的网站,产生了大量的stream量。 看起来,以下简单的脚本几乎适用于所有的浏览器:

 $(elem).onload = function() { doSomething(); } 

但这是IE9的潜在问题!

我们曾经报告过的唯一浏览器是IE9。 我们不感到惊讶吗? 看来解决这个问题的最好方法就是在定义了onload函数之后才能为图像分配一个src,如下所示:

 $(elem).onload = function() { doSomething(); } $(elem).attr('src','theimage.png'); 

似乎IE 9有时不会抛出onload事件,无论出于何种原因。 此页面上的其他解决scheme(例如Evan Carroll的解决scheme)仍然无效。 从逻辑上说,检查加载状态是否已经成功并触发了该函数,如果不是,则设置onload处理程序,但是即使这样做,我们在testing中演示了图像可能会在这两行js之间加载出现没有加载到第一行,然后在onload处理程序被设置之前加载。

我们发现获得你想要的最好的方法是在你设置onload事件触发器之前不定义图像的src。

我们刚刚停止支持IE8,所以我不能说IE9之前的版本,否则,在网站上使用的所有其他浏览器 – IE10和11以及Firefox,Chrome,Opera,Safari和其他手机浏览器人们正在使用 – 在分配onload处理程序之前设置src甚至不是一个问题。