gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:31:51 24 4
gpt4 key购买 nike

我想知道是否有一种方法可以控制用户打开网站时首先加载哪个图像。问题是我有一个简单的单页网站,打开第一个图像需要太多时间(大主页图像 - 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com