jQuery加载完整回调的图像

我在Ben Nadel的博客上发表评论,其中Stephen Rushing发布了一个加载器,但我无法弄清楚如何通过选择器和参数..我想我还需要一个completeCallback和errorCallback函数?

function imgLoad(img, completeCallback, errorCallback) { if (img != null && completeCallback != null) { var loadWatch = setInterval(watch, 500); function watch() { if (img.complete) { clearInterval(loadWatch); completeCallback(img); } } } else { if (typeof errorCallback == "function") errorCallback(); } } // then call this from anywhere imgLoad($("img.selector")[0], function(img) { $(img).fadeIn(); }); 

HTML:

  

JS:

 $(document).ready(function() { var newImage = "images/002.jpg"; $("#myImage").css("display","none"); $("a.tnClick").click(function() { // imgLoad here }); }) 

如果你想在显示之前加载它,你可以减少很多,如下所示:

 $(document).ready(function() { var newImage = "images/002.jpg"; //Image name $("a.tnClick").click(function() { $("#myImage").hide() //Hide it .one('load', function() { //Set something to run when it finishes loading $(this).fadeIn(); //Fade it in when loaded }) .attr('src', newImage) //Set the source so it begins fetching .each(function() { //Cache fix for browsers that don't trigger .load() if(this.complete) $(this).trigger('load'); }); }); }); 

.one()调用确保.load()只触发一次,因此没有重复的淡入淡出。 最后的.each()是因为某些浏览器不会为从缓存中获取的图像触发load事件,这就是您发布的示例中的轮询也正在尝试执行的操作。

使用图像加载事件时需要小心,因为如果在浏览器的缓存IE中找到图像并且(我被告知)Chrome将不会按预期触发事件。

由于我自己不得不面对这个问题,我通过检查DOM属性完成来解决(据说在大多数主流浏览器中工作):如果等于true,我只是取消绑定以前绑定的’load’事件。 见例子:

 $("#myimage").attr("src","http://www.mysite.com/myimage.jpg").load(doSomething); if ($("#myimage").get(0).complete) { // already in cache? $("#myimage").unbind("load"); doSomething(); } 

希望这可以帮助

我想要这个function,绝对不希望在页面渲染时加载所有图像。 我的图像是在amazon s3和一个大的照相馆,这将是很多不必要的请求。 我在这里创建了一个快速的jQuery插件来处理它:

 $("#image-1").loadImage('/path/to/new/image.jpg',function(){ $(this).css({height:'120px'});//alter the css styling after the image has loaded }); 

所以基本上,每当用户点击代表一组图片的缩略图时,我就会在那个时间点加载其他图像。 回调允许我在加载图像后更改css。

试试这个吗?

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

似乎上面的作品到处都是……