使用 jQuery 预加载背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9379855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:43:22  来源:igfitidea点击:

Preload background images with jQuery?

jquery

提问by Liam

I have a div thats currently set to display none, The Div has a background image that is approx 5000px wide, 2000px high.

我有一个当前设置为不显示的 div,该 Div 的背景图像宽约 5000 像素,高约 2000 像素。

I toggle the div display attirbute with jquery on a button click only with the image being so big the div loads and the image loads 1/2 seconds afterwards; is there a function where I can show a preloader until the image is ready and then display it?

我在按钮上使用 jquery 切换 div 显示属性,仅当图像太大时 div 加载,然后图像加载 1/2 秒;有没有可以显示预加载器直到图像准备好然后显示它的功能?

Thanks

谢谢

采纳答案by YuS

Try to use native javascript's Imageobject to preload the image.

尝试使用原生 javascript 的Image对象来预加载图像。

Also consider about to avoid using such huge images on the web by making tiles for example.

还要考虑通过制作瓷砖来避免在网络上使用如此巨大的图像。

回答by JustinW

This question was posted up a while back and answered just using vanilla javascript, but can be adapted to your scenario pretty easily.

这个问题是在不久前发布的,仅使用 vanilla javascript 就可以回答,但可以很容易地适应您的场景。

Preloading CSS Images

预加载 CSS 图像

$(document).ready( function() {

    var c = new Image();

    c.onload = function(){
        $("#Your Div ID").css("background-image", "url(Path to Background Image)");  
    }

    c.src = "Path to Background Image";

});