简体   繁体   English

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

[英]how to preload images for javascript slideshow

I wrote a simple JavaScript slideshow where the background is changed after some time via CSS background property.我写了一个简单的 JavaScript 幻灯片,其中背景在一段时间后通过 CSS 背景属性更改。 The problem is that on devices with low bandwidth the slideshow shows blank images when the images are not loaded.问题是在带宽较低的设备上,幻灯片在未加载图像时会显示空白图像。 My solution would be to preload all images and start the slideshow when all images are loaded.我的解决方案是预加载所有图像并在加载所有图像时开始幻灯片放映。 How can I preload the images and use them as background?如何预加载图像并将它们用作背景?

index.html:索引.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:幻灯片.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);
}

To load images dynamically you could use a recursive function like in the following example, which takes an array of image paths and loads them, then adds them to the document body after the page has loaded.要动态加载图像,您可以使用递归 function ,如下例所示,它采用图像路径数组并加载它们,然后在页面加载后将它们添加到文档正文中。 You can adapt the function to your own purpose, but the key is to pass index 0 at the start and then do whatever you need with the image inside your callback function, which receives a new array containing the images as your parameter.您可以根据自己的目的调整 function,但关键是在开始时传递索引 0,然后对回调 function 中的图像执行任何您需要的操作,它接收一个包含图像作为参数的新数组。

Callback approach:回调方法:

<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 approach: 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>

( Note: these methods replace the image url's in the array with the image themselves. If you wanted to keep both, you could use a map to store url/Image pairs) 注意:这些方法将数组中的图像 url 替换为图像本身。如果您想保留两者,可以使用 map 来存储 url/图像对)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM