开发者

Load all background-images at once with JS or CSS?

So right now I have a list with a bunch of Facilities. Each of these facilities has an image property which is simply just the name of it's image file. For example, facility.image == 'YogisBarAndGrill'. On pageload, I sent an array of strings (image names) via JSON and try to load all the images before the page and/or text is displayed.

Unfortunately, all my efforts are to no avail and the preloading doesn't work. Currently, the following is executed before document.ready()

(function() {
  var imagesPath, serviceURL, urlSegs;
  urlSegs = window.location.pathname.split("/");
  serviceURL = imagesPath = '';
  if (urlSegs.length === 2) {
    serviceURL = urlSegs[1] + '_images';
    imagesPath = urlSegs[1] === 'places' ? 'images/logos/' : 'images/categories/';
    $.getJSON(serviceURL, function(imageNames) {
      var i, _results;
      _results = [];
      for (i in imageNames) {
        if (i < imageNames.length) {
          _results.push((new Image()).src = imagesPath + imageNames[i] + '.png');
        }
      }
      return _results;
    });
  }
}).call(this);

The css for each list image looks like the following: background-image: url('images/logos/YogisBarAndGrill.png') or something similar.

Anyways - what I posted above doesn't work. No preloading is done. What I'm looking to achieve is having all images display at once OR even better wou开发者_如何转开发ld be to have the page display nothing at all until all images are done loading.

Thanks for any help!


When you say the preloading “doesn’t work”, what do you mean? What do you expect to happen?

“Preloading” means “loading before you need”. If the HTML elements that have these background images are on the same page as the JavaScript you’re using, then the browser will be downloading them as soon as it’s parsed the CSS, which is unlikely to be noticeably long after the JavaScript has stopped running.


You can do this by dynamically creating <img> elements for each image you want to load, let them complete their loading, then set background-image to the same urls. In the demo I use random images each run so they aren't cached.

Demo: http://jsfiddle.net/ThinkingStiff/Mp2cj/

Script:

function loadImages() {

    var images = getImages( 5 ),
        imgs = [],
        loaded = 0;

    createImgs();

    var timer = window.setInterval( function () {
        if( loaded == images.length ) {
            window.clearInterval( timer );
            setImages();
        };
    }, 50 );

    function createImgs() {
        for( var index = 0; index < images.length; index++ ) {
            imgs.push( document.createElement( 'img' ) );
            imgs[index].onload = function () { loaded++; };
            imgs[index].src = images[index];
        };
    };

    function setImages() {
        var divs = document.querySelectorAll( '#container div' );

        for( var index = 0; index < divs.length; index++ ) {
            divs[index].style.backgroundImage = 'url(' + images[index] + ')';
            console.log( 'div' );            
        };

        document.getElementById( 'container' ).removeAttribute( 'class' );
        document.getElementById( 'loading' ).setAttribute( 'class', 'hide' );
    };

    function getImages( count ) {
        var images = [],
            url = 'http://placekitten.com/';

        for( var index = 0, width, height; index < count; index++ ) {
            width = Math.floor( Math.random() * ( 1000 - 500 + 1 ) ) + 500;
            height = Math.floor( Math.random() * ( 1000 - 500 + 1 ) ) + 500;
            images.push( url + width + '/' + height );
        };

        return images;
    };

};

loadImages();

HTML:

<div id="loading">images loading...</div>
<div id="container" class="hide">
    <div></div><div></div><div></div><div></div><div></div>
</div>​

CSS:

.hide {
    display: none;
}

#container div {
    background-size: 100px 100px;
    display: inline-block;
    height: 100px;
    width: 100px;    
}​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜