在JavaScript中一个接一个地加载图像(Load images one after another in JavaScript)

编程入门 行业动态 更新时间:2024-10-20 11:42:14
在JavaScript中一个接一个地加载图像(Load images one after another in JavaScript)

我的问题是,我有多个图像,并希望加载像preloader,但问题是,我想在完成第一个图像后开始加载第二个图像。 在我当前的代码中,我将所有图像存储在一个数组中,并使用一个循环加载所有图像(将数组的所有图像的源代码赋予一个图像对象),然后开始加载所有图像。

My problem is, I have multiple images and want to load like preloader, but the problem is that I want to start load of the second image after completing the first one. In my current code I store all images in one array and using a loop load all images (give the source of all images of the array to an image object), and then all images start loading.

最满意答案

你想看看加载事件。

function loadImagesInSequence(images) { if (!images.length) { return; } var img = new Image(), url = images.shift(); img.onload = function(){ loadImagesInSequence(images) }; img.src = url; } loadImagesInSequence(['a.png', 'b.png', 'c.png']);

每当加载图像时,加载事件就会被触发。 当发生这种情况时,我们再次执行loadImagesInSequence()。 我们不会加载相同的图像两次,因为从我们简单地通过的数组中移除Array.shift() 。

You want to have a look at the load event.

function loadImagesInSequence(images) { if (!images.length) { return; } var img = new Image(), url = images.shift(); img.onload = function(){ loadImagesInSequence(images) }; img.src = url; } loadImagesInSequence(['a.png', 'b.png', 'c.png']);

whenever an image is loaded, the load event is fired. When that happens, we execute the loadImagesInSequence() again. We won't load the same image twice, as Array.shift() removed from the array we simply passed through.

更多推荐

本文发布于:2023-07-08 20:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1080252.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接一个   图像   加载   JavaScript   Load

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!