How to load all background images at one time

为君一笑 提交于 2019-12-05 12:29:56

For caching background images, I usually take the approach to preload them off screen as <img> and remove the container they're loaded in when the page has fully loaded :

#deposit {
  position: fixed;
  top: 100%;
}

$(function() {

var imghead = [
    "//www.psdgraphics.com/file/abstract-mosaic-background.png",
    "//www.psdgraphics.com/file/colorful-triangles-background.jpg",
    "//www.mrwallpaper.com/wallpapers/gradient-background.jpg"
    ];

$.each(imghead, function() {

    $('#deposit').append('<img src="' + this + '" alt="">');
});

$(window).on('load', function() {

    $('#deposit').remove();
});
});

The #deposit element could either be placed inside the markup or added dynamically :

$('body').append('<div id="deposit"></div>');

You could define them in preload containers in your CSS.

#preload-01 { background: url("http://www.psdgraphics.com/file/abstract-mosaic-background.png") no-repeat -9999px -9999px; }
#preload-02 { background: url("http://www.psdgraphics.com/file/colorful-triangles-background.jpg") no-repeat -9999px -9999px; }
#preload-03 { background: url("http://www.mrwallpaper.com/wallpapers/gradient-background.jpg") no-repeat -9999px -9999px; }

And just add them to your HTML.

Fiddle

UPDATE: You could add them as images and remove them once they are loaded, via a .load() function.

var i=0;
var imghead=[
    "http://www.psdgraphics.com/file/abstract-mosaic-background.png",
    "http://www.psdgraphics.com/file/colorful-triangles-background.jpg",
    "http://www.mrwallpaper.com/wallpapers/gradient-background.jpg"
];

$(imghead).each(function(key,val){
    $('body').append('<img class="preloader" src="'+val+'">');
    $('.preloader').load(function(){
        $(this).remove();
    });
});

function slideimg() {
    setTimeout(function () {
        jQuery('body').css('background-image', 'url('+imghead[i]+')');
        i++;
        if(i==imghead.length) i=0;
        slideimg();
    }, 6000);
}
slideimg();

Fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!