![](/img/trans.png)
[英]How to load image asynchronously using jquery while animating pictures as screenshot
[英]How to get remote image using jQuery asynchronously?
我想在页面上显示一个远程图像。 我使用Bootstrap 2.3.2传送带。 所有信息都来自另一个网站的RSS feed。 我将数据放入div中,如下所示:
...
<div id="newsItem-<?php echo $i;?>" class="item" data-src="<?php echo $feed[$i]->image; ?>" data-alt="<?php echo $feed[$i]->title; ?>">
</div>
...
图像加载时间太长。 页面加载约15秒。 因此,我决定在页面加载完成后加载图像。
要显示的图片可能有各种尺寸。 我想展示现有的最大的一个。
对于每个新闻项,所有图像可能具有不同但相似的尺寸,例如1024x768、620x350、528x350、527x350。
我已经编写了一个jQuery脚本来实现这一目标,但是出了点问题。
jQuery(function () {
jQuery("div[id^='newsItem-']").each(function () {
var r = jQuery(this).attr("data-src");
var r620 = r.replace(".jpg", "-620x350.jpg");
var r527 = r.replace(".jpg", "-527x350.jpg");
var r1024 = r.replace(".jpg", "-1024x678.jpg");
var r528 = r.replace(".jpg", "-528x350.jpg");
var altImg = jQuery(this).attr("data-alt");
if (pictureExists(r1024)){
r = r1024;
}
else if (pictureExists(r620)){
r = r620;
}
else if (pictureExists(r528)){
r = r528;
}
else if (pictureExists(r527)){
r = r527;
}
jQuery(this).prepend("<img src='" + r + "' alt='" + altImg + "' />");
jQuery(this).removeAttr("data-alt");
jQuery(this).removeAttr("data-src");
});
});
function pictureExists(url) {
var img = new Image();
img.src = url;
if (img.height !== 0) {
return false;
} else {
return true;
}
}
我想在轮播中显示最大的现有图片。
在加载图像之前,您无法知道图像的高度/宽度。 因此,它是一个异步过程。
在pictureExists函数中尝试以这种方式进行操作:
/ Create new image
var img = new Image();
// Create var for image source
var imageSrc = "http://example.com/blah.jpg";
// define what happens once the image is loaded.
img.onload = function() {
// Stuff to do after image load ( jQuery and all that )
// Within here you can make use of src=imageSrc,
// knowing that it's been loaded.
};
// Attach the source last.
// The onload function will now trigger once it's loaded.
img.src = imageSrc;
如果要使用上述方法,则必须实现promise结构,以解决图像加载的异步特性以获取高度/宽度
或者您可以使用这个小插件。 https://github.com/desandro/imagesloaded
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.