Search code examples
javascriptpreloadimage-preloader

Batch image preload function with numbering convention?


I am setting up a preload function for 180 images, but ideally the forloop should change the url with a counting integrer. "some_link/img" + n + ".jpg" ---> some_link/img001.jpg. All images are sequenced from 000 to 180.

var images = [];
var amount = 180;

function preload() {
    for (var i = 0; i < 180; i++) {
        images[i] = new Image();
        images[i].src = preload.arguments[i]; // <-- CUSTOM STRING HERE??
    }
}

preload(
    "...wp-content/uploads/2022/06/img000.jpg",
    "...wp-content/uploads/2022/06/img001.jpg",
    "...wp-content/uploads/2022/06/img002.jpg",
    "...wp-content/uploads/2022/06/img003.jpg",
    "...wp-content/uploads/2022/06/img004.jpg",
    "...wp-content/uploads/2022/06/img005.jpg"
)

Solution

  • make a simple loop and build a string using padStart to fill in the missing zeros.

    const month = 6;
    const year = 2022;
    const images = [];
    for (let i=0; i<180; i++) {
      const img = new Image();
      img.src = `...wp-content/uploads/${year}/${month.toString().padStart(2, '0')}/img${i.toString().padStart(3, '0')}.jpg`;
      images.push(img);
    }