Scenario: I have a HTML/CSS/JavaScript slideshow whose slides are div
s like
<div class="slide" id="slide1">
...
</div>
<div class="slide" id="slide2">
...
</div>
.
.
.
<div class="slide" id="slideN">
...
</div>
and these div
s contain img
s and video
s 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.