简体   繁体   中英

Does my jQuery Image preloader function work?

I've written a function which will load all large images from a lightbox gallery which are referenced by a link ( for those who don't know) after all small images are loaded $(window).load().

Here's the code:

$(window).load(function() {
    if ($('ul#gallery').length > 0) {
        // make a container, fill in images and attach it to the page body
        var c = $("<div />").attr({style: 'display: none', id: 'gallerypreload'});
        $("ul#gallery li > a").each(function() {
            $('<img />').attr('src', $(this).attr('href')).appendTo(c);
        });
        c.appendTo('body');
    }
});

The gallery looks like this:

<ul id="gallery">
    <li><a href="/img/image.jpg" title="Image title"><img src="img/thumbnail.jpg" alt="Image title" /></a></li>
    <li><a href="/img/image.jpg" title="Image title"><img src="img/thumbnail.jpg" alt="Image title" /></a></li>
    <li><a href="/img/image.jpg" title="Image title"><img src="img/thumbnail.jpg" alt="Image title" /></a></li>
    <li><a href="/img/image.jpg" title="Image title"><img src="img/thumbnail.jpg" alt="Image title" /></a></li>
    <li><a href="/img/image.jpg" title="Image title"><img src="img/thumbnail.jpg" alt="Image title" /></a></li>
</ul>

I want to do this, because the browser is supposed to load all thumbnails first and THEN preload larger images for viewing. Also, I've written some sort of fading effect which is triggered by $(window).load(), too.

My Question here is: Do ALL browsers preload images attached to the body in a container? Hence it is not displayed, theoretically they shouldn't load the images, or do they? Should I style visibility: hidden; width:0; height:0 visibility: hidden; width:0; height:0 visibility: hidden; width:0; height:0 or is my approach working?

Thanks.

You can force the preload by creating javascript image objects with the src you want to preload

$("ul#gallery li > a").each(function() {
    var preload = new Image();
    preload.src = $(this).attr('href');
    $('<img />').attr('src', preload.src).appendTo(c);
});

Then it shouldn't matter if the IMG tags are visible or not


Based on the comments below, this should be enough to preload the images:

$("ul#gallery li > a").each(function() {
    var preload = new Image();
    preload.src = $(this).attr('href');
});

or even

$("ul#gallery li > a").each(function() {
   (new Image()).src = $(this).attr('href');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM