我的问题是,我有多个图像,并希望加载像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.
更多推荐
发布评论