ChatGPT解决这个技术问题 Extra ChatGPT

Preloading images with jQuery

I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.

I saw this here (http://nettuts.com...):

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" });
  }
};

But, it looks a bit over-the-top for what I want!

I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!

$.each(arguments,function(){(new Image).src=this});

J
James

Quick and easy:

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'
]);

Or, if you want a jQuery plugin:

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

// Usage:

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

Doesn't the image element need to be inserted into the DOM to ensure the browser caches it?
I believe $('<img />') just creates an image element in memory (see link). It looks like '$('<img src="' + this + '" />') would actually create the element within a hidden DIV, because it is more "complicated". However, I don't think this is needed for most browsers.
That is a weird way of writing a jQuery plugin. Why not $.preload(['img1.jpg', 'img2.jpg']) ?
Make sure to call this inside $(window).load(function(){/*preload here*/}); because that way all images in the document are loaded first, it's likely that they are needed first.
@RegionalC - It may be a little safer to set the load event before setting the src just in case the image finishes loading before the load event is set? $('<img/>').load(function() { /* it's loaded! */ }).attr('src', this);
D
Dennis Rongo

Here's a tweaked version of the first response that actually loads the images into DOM and hides it by default.

function preload(arrayOfImages) {
    $(arrayOfImages).each(function () {
        $('<img />').attr('src',this).appendTo('body').css('display','none');
    });
}

hide() is more terse than css('display', 'none').
What's the advantage of inserting them into the DOM?
I also would like to know the advantage of inserting them into the DOM.
From my experience, preloading an image into the DOM makes the browser aware of its existence and for it to be properly cached. Otherwise, the image only exists in memory which only works for single page apps.
Dennis Rongo. Appending images to the DOM fixed random re-loading on Chrome. Thanks!
G
Gajus

Use JavaScript Image object.

This function allows you to trigger a callback upon loading all pictures. However, note that it will never trigger a callback if at least one resource is not loaded. This can be easily fixed by implementing onerror callback and incrementing loaded value or handling the error.

var preloadPictures = function(pictureUrls, callback) {
    var i,
        j,
        loaded = 0;

    for (i = 0, j = pictureUrls.length; i < j; i++) {
        (function (img, src) {
            img.onload = function () {                               
                if (++loaded == pictureUrls.length && callback) {
                    callback();
                }
            };

            // Use the following callback methods to debug
            // in case of an unexpected behavior.
            img.onerror = function () {};
            img.onabort = function () {};

            img.src = src;
        } (new Image(), pictureUrls[i]));
    }
};

preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
    console.log('a');
});

preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
    console.log('b');
});

Do the right thing, use JavaScript Image object. did you observe people doing the wrong thing in these answers?
Brilliant code. Am I correct in thinking that this will fire the onload event even if the image is cached? (Because img.onload is declared first). This is what my tests showed.
@alex potentially, yeah. If the goal is to pre-load (which suggests an order of performance) then I'd prefer to see a raw JS option instead of jQuery dependent options.
I loved this solution but I just discovered that it doesn't work in my Firefox. Is it just me or are others having the same issue?
@Gazillion give more details. How do you define "not working"? What is the FF version?
D
Dave

JP, After checking your solution, I was still having issues in Firefox where it wouldn't preload the images before moving along with loading the page. I discovered this by putting some sleep(5) in my server side script. I implemented the following solution based off yours which seems to solve this.

Basically I added a callback to your jQuery preload plugin, so that it gets called after all the images are properly loaded.

// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) { this.splice(i,1); }
  }
};

// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
  checklist = this.toArray();
  this.each(function() {
    $('<img>').attr({ src: this }).load(function() {
      checklist.remove($(this).attr('src'));
      if (checklist.length == 0) { callback(); }
    });
  });
};

Out of interest, in my context, I'm using this as follows:

$.post('/submit_stuff', { id: 123 }, function(response) {
  $([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
    // Update page with response data
  });
});

Hopefully this helps someone who comes to this page from Google (as I did) looking for a solution to preloading images on Ajax calls.


For those that are not interested in messing up the Array.prototype, instead, you can do: checklist = this.length And in the onload function: checklist-- Then: if (checklist == 0) callback();
Everything would be fine however adding new or removing existing methods to an object you don't own is one of the worst practices in JavaScript.
Nice and quick, but this code will never fire the callback if one of the images is broken or unable to load.
.attr({ src: this }).load(function() {...}) should be .load(function() {...}).attr({ src: this }) otherwise you will have caching problems.
r
rkcell

This one line jQuery code creates (and loads) a DOM element img without showing it:

$('<img src="img/1.jpg"/>');

@huzzah - You may be better off just using sprites. Less http requests. :)
y
yckart
$.fn.preload = function (callback) {
  var length = this.length;
  var iterator = 0;

  return this.each(function () {
    var self = this;
    var tmp = new Image();

    if (callback) tmp.onload = function () {
      callback.call(self, 100 * ++iterator / length, iterator === length);
    };

    tmp.src = this.src;
  });
};

The usage is quite simple:

$('img').preload(function(perc, done) {
  console.log(this, perc, done);
});

http://jsfiddle.net/yckart/ACbTK/


This is a really good answer, it really should be the top voted answer imho.
Some explaining words would have been nice.
Good answer, but I suggest using picsum.photos instead of lorempixel.com
a
alex

I have a small plugin that handles this.

It's called waitForImages and it can handle img elements or any element with a reference to an image in the CSS, e.g. div { background: url(img.png) }.

If you simply wanted to load all images, including ones referenced in the CSS, here is how you would do it :)

$('body').waitForImages({
    waitForAll: true,
    finished: function() {
       // All images have loaded.
    }  
});

Does this plugin cause images that haven't appeared on the page yet to be loaded, or only attach events to images which were already going to be loaded?
@DaveCameron It doesn't respect if the images are visible or not. You could easily fork it and make that change - just add :visible to the custom selector.
This plugin looks very interesting. However, the jquery documentation highlights that the load event, when applied to images: "doesn't work consistently nor reliably cross-browser". How has the plugin managed to get around that?
@EleventyOne Check the source with regard to the custom selector.
@alex How does this plugin load images that are set in the css on :hover of an element? It does not work for me
i
itsme

you can load images in your html somewhere using css display:none; rule, then show them when you want with js or jquery

don't use js or jquery functions to preload is just a css rule Vs many lines of js to be executed

example: Html

<img src="someimg.png" class="hide" alt=""/>

Css:

.hide{
display:none;
}

jQuery:

//if want to show img 
$('.hide').show();
//if want to hide
$('.hide').hide();

Preloading images by jquery/javascript is not good cause images takes few milliseconds to load in page + you have milliseconds for the script to be parsed and executed, expecially then if they are big images, so hiding them in hml is better also for performance, cause image is really preloaded without beeing visible at all, until you show that!


More info on this approach can be found here: perishablepress.com/…
But you need to be aware that this technique has a major drawback: your page will not be completely loaded until all images are loaded. Depending on the number of images to preload and their size, this could take some time. Even worse, if the tag does not specify a height and width some browsers might wait until the image is fetched before rendering the rest of the page.
@Alex you anyway need to load the img, you are free to choose if to load them with html and avoid any kind of blinking and half loaded images , or if you want to get more speed going for a not stable solution
also i really think creating html tags with javascript is unreadable at all just my 2 cents
I needed a very quick solution for a very complex project and this was it.
a
alzclarke

this jquery imageLoader plugin is just 1.39kb

usage:

$({}).imageLoader({
    images: [src1,src2,src3...],
    allcomplete:function(e,ui){
        //images are ready here
        //your code - site.fadeIn() or something like that
    }
});

there are also other options like whether you want to load the images synchronously or asychronously and a complete event for each individual image.


@Ian because the document is already ready by the time the callback is fired. $(document).ready is used to make sure your DOM is loaded. When it comes to the callback, that mean that all images are loaded which means that yoru DOM is loaded so no need for document.ready inside a callback.
@AamirAfridi There is no guarantee that the document is ready in the callback...where are you inferring that from? There's nothing on the plugin's page that says the allcomplete callback is executed after the DOM is ready. There's a pretty good chance that the images finish loading after the DOM is ready, but there's no reason to assume. I don't know why you think callbacks are magical and are executed after the DOM is ready...can you explain where you're getting that from? Just because the images are loaded doesn't mean the DOM is ready
@AamirAfridi And the documentation for the plugin even says: NB to use this as an image preloader simply put your $(document).ready(function(){}); into your 'allcomplete' event : > simples! ... it directly recommends what this answer shows.
@Ian its always wise to call your plugin(s) inside $(document).ready to avoid all this.
@AamirAfridi That makes no sense for this situation. The plugin is a pre loader. You want to execute it as soon as possible. And there are plenty of things that don't depend on the DOM that you want to fire as soon as possible, and then when the DOM is ready, do something.
i
izb

A quick, plugin-free way to preload images in jQuery and get a callback function is to create multiple img tags at once and count the responses, e.g.

function preload(files, cb) {
    var len = files.length;
    $(files.map(function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

preload(["one.jpg", "two.png", "three.png"], function() {
    /* Code here is called once all files are loaded. */
});
​    ​

Note that if you want to support IE7, you'll need to use this slightly less pretty version (Which also works in other browsers):

function preload(files, cb) {
    var len = files.length;
    $($.map(files, function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

d
dmgig

Thanks for this! I'd liek to add a little riff on the J-P's answer - I don't know if this will help anyone, but this way you don't have to create an array of images, and you can preload all your large images if you name your thumbs correctly. This is handy because I have someone who is writing all the pages in html, and it ensures one less step for them to do - eliminating the need to create the image array, and another step where things could get screwed up.

$("img").each(function(){
    var imgsrc = $(this).attr('src');
    if(imgsrc.match('_th.jpg') || imgsrc.match('_home.jpg')){
      imgsrc = thumbToLarge(imgsrc);
      (new Image()).src = imgsrc;   
    }
});

Basically, for each image on the page it grabs the src of each image, if it matches certain criteria (is a thumb, or home page image) it changes the name(a basic string replace in the image src), then loads the images.

In my case the page was full of thumb images all named something like image_th.jpg, and all the corresponding large images are named image_lg.jpg. The thumb to large just replaces the _th.jpg with _lg.jpg and then preloads all the large images.

Hope this helps someone.


A
Alex
    jQuery.preloadImage=function(src,onSuccess,onError)
    {
        var img = new Image()
        img.src=src;
        var error=false;
        img.onerror=function(){
            error=true;
            if(onError)onError.call(img);
        }
        if(error==false)    
        setTimeout(function(){
            if(img.height>0&&img.width>0){ 
                if(onSuccess)onSuccess.call(img);
                return img;
            }   else {
                setTimeout(arguments.callee,5);
            }   
        },0);
        return img; 
    }

    jQuery.preloadImages=function(arrayOfImages){
        jQuery.each(arrayOfImages,function(){
            jQuery.preloadImage(this);
        })
    }
 // example   
    jQuery.preloadImage(
        'img/someimage.jpg',
        function(){
            /*complete
            this.width!=0 == true
            */
        },
        function(){
            /*error*/
        }
    )

Welcome to Stack Overflow! Rather than only post a block of code, please explain why this code solves the problem posed. Without an explanation, this is not an answer.
C
Cristan

I use the following code:

$("#myImage").attr("src","img/spinner.gif");

var img = new Image();
$(img).load(function() {
    $("#myImage").attr("src",img.src);
});
img.src = "http://example.com/imageToPreload.jpg";

Bind to the load event first, then set the src.
C
Christian Landgren

I would use an Manifest file to tell (modern) web browsers to also load all relevant images and cache them. Use Grunt and grunt-manifest to do this automatically and never worry again about preload scripts, cache invalidators, CDN etc.

https://github.com/gunta/grunt-manifest


Z
Zymotik

This works for me even in IE9:

$('<img src="' + imgURL + '"/>').on('load', function(){ doOnLoadStuff(); });

This will fail eventually due to caching, always bind the load event before setting the src attribute.
C
Community

I wanted to do this with a Google Maps API custom overlay. Their sample code simply uses JS to insert IMG elements and the image placeholder box is displayed until the image is loaded. I found an answer here that worked for me : https://stackoverflow.com/a/10863680/2095698 .

$('<img src="'+ imgPaht +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});

This preloads an image as suggested before, and then uses the handler to append the img object after the img URL is loaded. jQuery's documentation warns that cached images don't work well with this eventing/handler code, but it's working for me in FireFox and Chrome, and I don't have to worry about IE.


This won't work well with cached images as you've found out. the workaround is to bind the load event first, then set the src attribute.
M
Mohammad
function preload(imgs) {
    $(imgs).each(function(index, value) {
        $('<img />').attr('src', value).appendTo('body').css('display', 'none');
    });
}

.attr('src',value) not .attr('src',this)

just to point it out :)


Scope this inside the callback that is passed to $.each is assigned to the value that is being iterated.
? $(['img1.jpg','img2.jpg','img3.jpg']).each(function (index,value) { console.log(value);//img1.jpg console.log(this);//String { 0="i", 1="m", 2="g", more...} $('').attr('src',this).appendTo('body').css('display','none'); });
Hm. I guess you are right here. For example $("div").each(function(i, el){ console.log(el == this);}); generates all trues; Iteration over array seems to behave differently.
F
Francesco Orsi

I usually use this snippet of code on my projects for the loading of the images in a page. You can see the result here https://jsfiddle.net/ftor34ey/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<img src="https://live.staticflickr.com/65535/50020763321_d61d49e505_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50021019427_692a8167e9_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020228418_d730efe386_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020230828_7ef175d07c_k_d.jpg" width="100" />

<div style="background-image: url(https://live.staticflickr.com/65535/50020765826_e8da0aacca_k_d.jpg);"></div>
<style>
    .bg {
        background-image: url("https://live.staticflickr.com/65535/50020765651_af0962c22e_k_d.jpg");
    }
</style>
<div class="bg"></div>

<div id="loadingProgress"></div>

The script save in an array all the src and background-image of the page and load all of them.

You can see/read/show the progress of the loading by the var loadCount.

let backgroundImageArray = [];

function backgroundLoading(i) {

    let loadCount = 0;

    let img = new Image();
    $(img).on('load', function () {

        if (i < backgroundImageArray.length) {

            loadCount = parseInt(((100 / backgroundImageArray.length) * i));
            backgroundLoading(i + 1);

        } else {

            loadCount = 100;
            // do something when the page finished to load all the images
            console.log('loading completed!!!');
            $('#loadingProgress').append('<div>loading completed!!!</div>');

        }

        console.log(loadCount + '%');
        $('#loadingProgress').append('<div>' + loadCount + '%</div>');

    }).attr('src', backgroundImageArray[i - 1]);

}

$(document).ready(function () {

    $('*').each(function () {

        var backgroundImage = $(this).css('background-image');
        var putInArray = false;

        var check = backgroundImage.substr(0, 3);

        if (check == 'url') {

            backgroundImage = backgroundImage.split('url(').join('').split(')').join('');
            backgroundImage = backgroundImage.replace('"', '');
            backgroundImage = backgroundImage.replace('"', '');

            if (backgroundImage.substr(0, 4) == 'http') {
                backgroundImage = backgroundImage;
            }
            putInArray = true;

        } else if ($(this).get(0).tagName == 'IMG') {

            backgroundImage = $(this).attr('src');
            putInArray = true;

        }

        if (putInArray) {
            backgroundImageArray[backgroundImageArray.length] = backgroundImage;
        }

    });

    backgroundLoading(1);

});

G
Guy Morita

5 lines in coffeescript

array = ['/img/movie1.png','/img/movie2.png','/img/movie3.png']

$(document).ready ->
  for index, image of array
    img[index] = new Image()
    img[index].src = image

Can you expand on how solution works to resolve the question in the OP? And possibly comment your code so others can more easily understand it?
P
Peter Gruppelaar

For those who know a little bit of actionscript, you can check for flash player, with minimal effort, and make a flash preloader, that you can also export to html5/Javascript/Jquery. To use if the flash player is not detected, check examples on how to do this with the youtube role back to html5 player:) And create your own. I do not have the details, becouse i have not started yet, if i dont forgot, i wil post it later and will try out some standerd Jquery code to mine.


This is not a solution. Browser don't support Flash player by default. It can be easily achieve with JavaScript which is the native browser language.
I remember the Flash haters from 2012... it was not normal... everywhere i went i was attacked when i even used the word Flash.