javascript - 控制首先加载哪个图像

标签 javascript jquery html

我想知道是否有一种方法可以控制用户打开网站时首先加载哪个图像。问题是我有一个简单的单页网站,打开第一个图像需要太多时间(大主页图像 - example )。我想先加载此图像,然后加载网站中的其他图像,我是否应该使用 Jquery 为每个图像手动执行此操作(在 之后使用 $.attr("src") document.ready)?或者有更好的方法吗?

最佳答案

Control which image loads first

如果您想控制首先加载哪些图像并同步加载图像,请尝试此操作。 Working JsFiddle

var loaded = 0;
var imgSrcArray = ["https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Small_icosihemidodecahedron.png/100px-Small_icosihemidodecahedron.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Small_cubicuboctahedron.png/100px-Small_cubicuboctahedron.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Small_dodecahemidodecahedron.png/100px-Small_dodecahemidodecahedron.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/Small_rhombicuboctahedron.png/100px-Small_rhombicuboctahedron.png"];


$('div img').on('load',function(){
 loaded++;
 var indexOfThisImg = imgSrcArray.indexOf($(this).attr('src'));
 $('#output').append("loaded image " +indexOfThisImg + '<br/>');
 loadNextImg(loaded);
});

function loadNextImg(index){
   $('div img:eq('+index+')').attr('src',imgSrcArray[index]); 
   // if the imag tags are not continuous and you want to load the images in random position in an order then you can maintain the order of the images in a separate array and then use that indexes to load the images. 
}

$('div img:eq(0)').attr('src',imgSrcArray[0]); 
//trigger the load of first image, which starts the chain reaction   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img />
<img />
<img />
<img />
</div>
<div id="output">
  
</div>

这个想法是将所有图像 src 保存在一个数组中并加载第一个图像,并在图像的加载事件中增加数组索引并加载第二个图像,依此类推。这样我们就可以控制应加载的图像的顺序。让我知道这是否有帮助

关于javascript - 控制首先加载哪个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785630/

相关文章:

javascript - 如何获取 Jade 中动态生成的输入的值

javascript - Flex 项目包括 SWFAddress.js

javascript - 进度回调在 jquery-file-upload 插件中始终显示 100% 上传

javascript - 从下拉列表中选择选项,具体取决于两个下拉列表,这将显示 mysql 数据库 php 中的主题选项

javascript - 从 AWS S3 插入图像失败(使用 SSL)

javascript - JS : Submit HTML file and place file code within div

javascript - 未捕获的类型错误 : Cannot read property 'AutoFill' of undefined

jQuery 从数组中旋转类

javascript - 将字符串 "Microsoft"替换为 "W3Schools Test$' "

java - 使用 jsoup java 从 &lt;!-- --> 注释中提取 HTML 到结束标记