如何为javascript幻灯片预加载图片

问题描述 投票:0回答:1

我写了一个简单的JavaScript幻灯片,通过CSS背景属性在一段时间后改变背景。问题是在低带宽的设备上,当图像未加载时,幻灯片会显示空白图像。我的解决方案是预加载所有图片,并在所有图片加载完毕后启动幻灯片。我怎样才能预加载图片并将它们作为背景?

index.html:

<html>
  <head>
  </head>
  <body>
    <div class="jumbotron" style="width:200pt; height:200pt"></div>

    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
    <script src="slideshow.js"></script>
  </body>
</html>

slideshow.js:

$(window).on("load", function () {
  // List of image paths.
  var background_images = ["image1.jpg", "image2.jpg"]

  // Every X miliseconds change the background image.
  var X = 4000
  backgroundImageIdx = 0;
  window.setInterval(function () {
    $(".jumbotron").css("background-image", "url(" + background_images[backgroundImageIdx] + ")");
    backgroundImageIdx++;
    if (backgroundImageIdx >= nrOfBackgroundImages) {
      backgroundImageIdx = 0;
    }
  }, X);
}
javascript html jquery image preload
1个回答
0
投票

为了动态加载图片,你可以使用一个递归函数,就像下面的例子,它接收一个图片路径数组并加载它们,然后在页面加载后将它们添加到文档主体中。你可以根据自己的目的对函数进行调整,但关键是在开始的时候传递索引0,然后在你的回调函数里面对图片做任何你需要的事情,回调函数会接收一个包含图片的新数组作为参数。

回调方式。

<script>
    let images = [
        'images/DSCF1589.jpg',
        'images/DSCF1590.jpg',
        'images/DSCF1591.jpg',
        'images/DSCF1592.jpg',
        'images/DSCF1593.jpg',
        'images/DSCF1594.jpg',
    ];

    // Loads the images one at a time, then calls the callback function when all images
    // have been loaded
    function loadImages(images, index, callback) {
        if (index < images.length) {
            let img = new Image();
            img.src = images[index];
            images[index] = img;
            images[index].onload = function() {
                loadImages(images, ++index, callback);
            };
        } else {
            callback(images);
        }
    }
    window.onload = function() {
        loadImages(images, 0, (images) => {
            // Your slideshow code goes here. This is just example code
            // of adding the images to your document once they are all loaded
            images.forEach((item) => {
               document.querySelector('body').appendChild(item);
            });
        });
    };
</script>

Promise方法:

<script>
    let images = [
        'images/DSCF1589.jpg',
        'images/DSCF1590.jpg',
        'images/DSCF1591.jpg',
        'images/DSCF1592.jpg',
        'images/DSCF1593.jpg',
        'images/DSCF1594.jpg',
    ];

    function loadImages(images) {
        return new Promise((resolve, reject) => {
            (function loadEach(images, index) {
                if (index < images.length) {
                    let img = new Image();
                    img.src = images[index];
                    images[index] = img;
                    images[index].onload = function() {
                        loadEach(images, ++index);
                    };
                    images[index].onerror = (err) => reject(err);
                } else {
                    resolve(images);
                }
            })(images, 0)
        });
    }
    window.onload = function() {
        loadImages(images).then((images) => {
            // Your slideshow code goes here. This is just example code
            // of adding the images to your document once they are all loaded
            images.forEach((item) => {
                document.querySelector('body').appendChild(item);
            });
        }).catch((err) => console.error(err));
    };
</script>

(请注意,这些方法将数组中的图片url替换为图片本身。 这些方法将数组中的图片url替换为图片本身。如果你想同时保留两个图片,你可以使用一个map来存储urlImage对)

© www.soinside.com 2019 - 2024. All rights reserved.