使用 JavaScript 进行智能图像加载
smart image loading with javascript
这是我的场景,我们有一张猫的主图像(假设它的 1000px x 1000px)和 10 张猫的缩略图(100px x 100px)。 选择拇指后,主图像会发生变化。目前,图像正在预加载
$('#showcase .thumbnail').each(function(index,el){
var mainImg = $(el)[0].src.replace('small','large');
var img = new Image();
img.src = mainImg;
});
这将加载我的大版本的缩略图。
我有一个<select>
标签,有四个<option>
,当选择一个选项时,10 个缩略图图像和主图像都会改变。用户对猫没有兴趣,几乎立即选择狗选项。
问题
可以将猫的图像推到图像列表的后面以下载并优先考虑狗的图像吗?
提前谢谢。
假设选择如下所示:
<select id="select">
<option value="">Please select</option>
<option value="dogs">Dogs</option>
<option value="cats">Cats</option>
<option value="fishes">Fishes</option>
</select>
并且每个图像都有一个与值对应的类名(例如 <img class="cat" src=... />
)然后这里有一些代码(没有彻底测试):
// is something selected in the dropdown
var selection = false;
// observe the dropdown
$('#select').change(function(){
// the user selected something -> store it
if(this.value) {
selection = this.value;
}
// back to default
else {
selection = false;
}
});
// store the images
var images = $('#showcase .thumbnail');
// stack for the unreplaced images
var stack = [];
// first run
function replaceImages(images, currentIndex) {
// we're finished
if (imageURLarray.length == 0 || images.length == currentIndex) {
return false;
}
// there's no selection at all or we have a selection and the current image has the corresponding class -> replace it
if(!selection || (selection && $(images[currentIndex]).hasClass(selection))) {
var mainImg = $(images[currentIndex])[0].src.replace('small','large');
var img = new Image();
img.src = mainImg;
// wait for loading. If we wouldn't wait, all image src's would be replaced in a second and our prioritizing magic wouldn't happen
img.onload = function(e){
// image has loaded -> next image
replaceImages(images, currentIndex++);
}
}
// there's a selection and the class doesn't match -> store the image in the stack
else {
stack.push(currentIndex);
}
}
// run the function
replaceImages(images, 0) {
// process the stack, i.e. the non-replaced images
$(stack).each(function(index, val){
var mainImg = $(images[val]).src.replace('small','large');
var img = new Image();
img.src = mainImg;
});
相关文章:
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 在检索数据时是否可以停止图像加载请求
- 如何让我的网站上的WEBP图像加载在morzilla firefox中有一个可能的解决方案吗?如果是,那么如何
- jQuery:获取图像加载错误的详细信息
- 在safari和chrome中,js图像加载产生了奇怪的结果
- 图像加载不适用于 IE 8 或更低版本
- 这个图像加载功能有什么作用
- JavaScript 图像加载器不起作用
- 动态图像加载是否会减少服务器过载
- 跨来源图像加载被拒绝-仅限iPhone-简单图像上传
- 纯javascript的进度图像加载程序仅当用户单击提交html表单时
- 使用JavaScript延迟图像加载
- 如果当前图像加载缓慢,如何加载其他图像
- HTML图像加载触发一个错误
- 将图像加载到localStorage,并将图像src设置到该位置
- jquery图像加载检查错误
- 将图像加载到织物画布背景中
- 需要在bootstrap css中单击时将图像加载为模态
- 正在显示加载..在将新图像加载到网站时播放动画
- 砖石事件:在图像加载和布局完成后调用事件