The definitive best way to preload images using Ja

2019-01-02 20:21发布

I'm fully aware that this question has been asked and answered everywhere, both on SO and off. However, every time there seems to be a different answer, e.g. this, this and that.

I don't care whether it's using jQuery or not - what's important is that it works, and is cross-browser.]

So, what is the best way to preload images?

8条回答
一个人的天荒地老
2楼-- · 2019-01-02 20:24

Spriting

As others have mentioned, spriting works quite well for a variety of reasons, however, it's not as good as its made out to be.

  • On the upside, you end up making only one HTTP request for your images. YMMV though.
  • On the down side you are loading everything in one HTTP request. Since most current browsers are limited to 2 concurrent connections the image request can block other requests. Hence YMMV and something like your menu background might not render for a bit.
  • Multiple images share the same color palette so there is some saving but this is not always the case and even so it's negligible.
  • Compression is improved because there is more shared data between images.

Dealing with irregular shapes is tricky though. Combining all new images into the new one is another annoyance.

Low jack approach using <img> tags

If you are looking for the most definitive solution then you should go with the low-jack approach which I still prefer. Create <img> links to the images at the end of your document and set the width and height to 1x1 pixel and additionally put them in a hidden div. If they are at the end of the page, they will be loaded after other content.

查看更多
骚的不知所云
3楼-- · 2019-01-02 20:29

Here goes my simple solution with a fade in on the image after it is loaded.

    function preloadImage(_imgUrl, _container){
        var image = new Image();
            image.src = _imgUrl;
            image.onload = function(){
                $(_container).fadeTo(500, 1);
            };
        }
查看更多
荒废的爱情
4楼-- · 2019-01-02 20:39

In my opinion, using Multipart XMLHttpRequest introduced by some libraries will be a preferred solution in the following years. However IE < v8, still don't support data:uri (even IE8 has limited support, allowing up to 32kb). Here is an implementation of parallel image preloading - http://code.google.com/p/core-framework/wiki/ImagePreloading , it's bundled in framework but still worth taking a look.

查看更多
查无此人
5楼-- · 2019-01-02 20:41

For my use case I had a carousel with full screen images that I wanted to preload. However since the images display in order, and could take a few seconds each to load, it's important that I load them in order, sequentially.

For this I used the async library's waterfall() method (https://github.com/caolan/async#waterfall)

        // Preload all images in the carousel in order.
        image_preload_array = [];
        $('div.carousel-image').each(function(){
            var url = $(this).data('image-url');
            image_preload_array.push(function(callback) {
                var $img = $('<img/>')
                $img.load(function() {
                    callback(null);
                })[0].src = url;
            });
        });
        async.waterfall(image_preload_array);

This works by creating an array of functions, each function is passed the parameter callback() which it needs to execute in order to call the next function in the array. The first parameter of callback() is an error message, which will exit the sequence if a non-null value is provided, so we pass null each time.

查看更多
君临天下
7楼-- · 2019-01-02 20:46

Unfortunately, that depends on your purpose. If you plan to use the images for purposes of style, your best bet is to use sprites. http://www.alistapart.com/articles/sprites2

However, if you plan to use the images in <img> tags, then you'll want to pre-load them with

function preload(sources)
{
  var images = [];
  for (i = 0, length = sources.length; i < length; ++i) {
    images[i] = new Image();
    images[i].src = sources[i];
  }
}

(modified source taken from What is the best way to preload multiple images in JavaScript?)

using new Image() does not involve the expense of using DOM methods but a new request for the image specified will be added to the queue. As the image is, at this point, not actually added to the page, there is no re-rendering involved. I would recommend, however, adding this to the end of your page (as all of your scripts should be, when possible) to prevent it from holding up more critical elements.

Edit: Edited to reflect comment quite correctly pointing out that separate Image objects are required to work properly. Thanks, and my bad for not checking it more closely.

Edit2: edited to make the reusability more obvious

Edit 3 (3 years later):

Due to changes in how browsers handle non-visible images (display:none or, as in this answer, never appended to the document) a new approach to pre-loading is preferred.

You can use an Ajax request to force early retrieval of images. Using jQuery, for example:

jQuery.get(source);

Or in the context of our previous example, you could do:

function preload(sources)
{
  jQuery.each(sources, function(i,source) { jQuery.get(source); });
}

Note that this doesn't apply to the case of sprites which are fine as-is. This is just for things like photo galleries or sliders/carousels with images where the images aren't loading because they are not visible initially.

Also note that this method does not work for IE (ajax is normally not used to retrieve image data).

查看更多
登录 后发表回答