Preloading images from jquery

Asked 2 years ago, Updated 2 years ago, 44 views

I'm looking for the fastest and easiest way to pre-load images from JavaScript. I don't know if this is important, but I'm using jquery.

I found the following source on the Internet.

function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("<img>").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};

Is there any other sauce that's simpler and faster?

javascript jquery

2022-09-22 22:07

1 Answers

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // // Alternatively you could use:
        // // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

If you use this or jQuery, you can also use the following method.

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();


2022-09-22 22:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.