0

Scenario: I have a HTML/CSS/JavaScript slideshow whose slides are divs like

<div class="slide" id="slide1">
   ...
</div>
<div class="slide" id="slide2">
   ... 
</div>
.
.
.
<div class="slide" id="slideN">
   ... 
</div>

and these divs contain imgs and videos and I what I want to do is pre-load these elements so that they'll already be up and showing when the user goes to the next slide. I'm wondering if there exists a general procedure for doing this, a procedure where I can add or substract media elements and it still works because the procedure doesn't rely on target a specific element's src attribute or something. From what I understand, it requires doing a hacky thing where you remove and then add back in the src attribute like

$(function(){
  var $images = $('.slide img'), 
      $videos = $('.slide video'), 
      k = 0,
      n = $images.length + $videos.length; 
  $images.each(function(){
    var src = $(this).attr('src');
    $(this).attr('src') = '';
    $(this).attr('src') = src;
    console.log(k++/n * 100 + "%"); 
  });
  $videos.each(function(){
    var src = $(this).attr('src');
    $(this).attr('src') = '';
    $(this).attr('src') = src;
    console.log(k++/n * 100 + "%"); 
  });
  $('.slide').show(); // now we're ready!
});

Is that correct? Why or why not?

(On a related note, is it possible to merge two jQuery resulting sets, so that I don't have to write two each loops above?)

The way I've seen it done always involves an array of the URLs of images to be loaded, like the example

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

//-- usage --//
preload(
    "http://domain.tld/gallery/image-001.jpg",
    "http://domain.tld/gallery/image-002.jpg",
    "http://domain.tld/gallery/image-003.jpg"
)

from JavaScript Preloading Images

and that just doesn't seem general enough to me.

Community
  • 1
  • 1
user6048670
  • 2,861
  • 4
  • 16
  • 20
  • `$('.slide img, .slide video')` will collect them both into one query. – DBS Mar 25 '16 at 14:31
  • As per your code browser should be triggering requests to load all images in the HTML. Can you check in your network tab is all images are loaded even without this code? – sabithpocker Mar 25 '16 at 14:47

1 Answers1

0

You can load each one immediately and put them in a "bank" section with display:none set so they're invisible. The browser will cache them, and they'll be available to display as soon as you're ready.

Harris
  • 1,775
  • 16
  • 19