Preloading content with images with jQuery
I am using .load() in jQuery to load in html content, but in this content there are 3/4 images embedded. The success event only fires on .load() when all the html is loaded in and not actually the images, does anyone know a way of preloading the full content of a page?
$('#ajax_loader').hide().load('page.html',fun开发者_运维百科ction(){
$(this).fadeUp(1000);
});
This is my simple code (rest of it is in the full app), loading in the following code (ie. page.html)
<div>
<div id="slideshow">
<img src="images/img1.jpg" />
<img src="images/img2.jpg" />
<img src="images/img3.jpg" />
</div>
<p>This is some sample content</p>
</div>
I suggest that you don't use a fadeIn
animation after the images are loaded because of performance degradation it brings. It is usually a good idea to fadeIn
the content then start loading the images to ensure that the animation is smooth for as many users as possible.
Having said that, of course you can accomplish your original goal if you want to stick with it:
Use a 1x1 blank image as the image src
attribute and store the real url in the title
.
<div>
<div id="slideshow">
<img src="blank.gif" title="images/img1.jpg" />
<img src="blank.gif" title="images/img2.jpg" />
<img src="blank.gif" title="images/img3.jpg" />
</div>
<p>This is some sample content</p>
</div>
And your code becomes:
$('#ajax_loader').hide().load('page.html', function(){
var c = 0;
var images = $("#slideshow img");
images.load(function(){
if (++c == images.length) {
$('#ajax_loader').fadeIn(1000);
}
});
images.each(function(){
this.src = this.title;
});
});
The images are loaded with separate HTML requests, and obviously the browser can't even start loading them until the HTML in the response has been parsed.
If you know the URLs of the images before you load the content, then you can preload them by creating "Image" elements and waiting for them to load (that is, by handling their "load" events individually).
var imgUrls = [ "images/img1.jpg", "images/img2.jpg", "images/img3.jpg" ];
var c = 0;
for (var i = 0; i < imgUrls.length; ++i) {
var img = new Image();
img.onload = function() {
c += 1;
if (c == imgUrls.length) {
// at this point all images are loaded
// ...
}
};
img.src = imgUrls[i];
}
edit — @galambalazs pointed out that the closure around the handler was (in this case) unnecessary.
Check out this similar situation
It seems that the main fix to your problem would be the correct use of the .ready
and the .load
operator. If used properly, you can wait until all elements and media items are loaded into the browser before a response is passed to its handler. I don't want to plagerize too much :) and its a really great answer.
精彩评论