Javascript 如何检查背景图像是否已加载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5057990/
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
How can I check if a background image is loaded?
提问by Peter
I want to set a background image on the body tag, then run some code - like this:
我想在 body 标签上设置一个背景图像,然后运行一些代码 - 像这样:
$('body').css('background-image','http://picture.de/image.png').load(function() {
alert('Background image done loading');
// This doesn't work
});
How can I make sure the background image is fully loaded?
如何确保背景图像已完全加载?
回答by jcubic
try this:
尝试这个:
$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {
$(this).remove(); // prevent memory leaks as @benweet suggested
$('body').css('background-image', 'url(http://picture.de/image.png)');
});
this will create new image in memory and use load event to detect when the src is loaded.
这将在内存中创建新图像并使用 load 事件来检测 src 何时加载。
回答by alex
I have a jQuery plugincalled waitForImages
that can detect when background images have downloaded.
我有一个名为的jQuery 插件waitForImages
,可以检测背景图像何时下载。
$('body')
.css('background-image','url(http://picture.de/image.png)')
.waitForImages(function() {
alert('Background image done loading');
// This *does* work
}, $.noop, true);
回答by Colin
Something like this:
像这样的东西:
var $div = $('div'),
bg = $div.css('background-image');
if (bg) {
var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
$img = $('<img>').attr('src', src).on('load', function() {
// do something, maybe:
$div.fadeIn();
});
}
});
回答by Adrian Pacala
There are no JS callbacks for CSS assets.
CSS 资产没有 JS 回调。
回答by Jon Catmull
Here is a small plugin I made to allow you to do exactly this, it also works on multiple background images and multiple elements:
这是我制作的一个小插件,可以让您做到这一点,它也适用于多个背景图像和多个元素:
Read the article:
阅读文章:
http://catmull.uk/code-lab/background-image-loaded/
http://catmull.uk/code-lab/background-image-loaded/
or go straight to the plugin code:
或者直接看插件代码:
http://catmull.uk/downloads/bg-loaded/bg-loaded.js
http://catmull.uk/downloads/bg-loaded/bg-loaded.js
So just include the plugin and then call it on the element:
所以只需包含插件,然后在元素上调用它:
<script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
<script type="text/javascript">
$('body').bgLoaded();
</script>
Obviously download the plugin and store it on your own hosting.
显然下载插件并将其存储在您自己的主机上。
By default it adds an additional "bg-loaded" class to each matched element once the background is loaded but you can easily change that by passing it a different function like this:
默认情况下,它会在背景加载后为每个匹配的元素添加一个额外的“bg-loaded”类,但您可以通过向它传递一个不同的函数来轻松更改它,如下所示:
<script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
<script type="text/javascript">
$('body').bgLoaded({
afterLoaded : function() {
alert('Background image done loading');
}
});
</script>
Here is a codepen demonstrating it working.
这是一个演示它工作的代码笔。
回答by godblessstrawberry
pure JS solution that will add preloader, set the background-image and then set it up for garbage collection along with it's event listener:
纯 JS 解决方案,将添加预加载器,设置背景图像,然后将其设置为垃圾收集及其事件侦听器:
Short version:
精简版:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
let bgElement = document.querySelector("body");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
preloaderImg.addEventListener('load', (event) => {
bgElement.style.backgroundImage = `url(${imageUrl})`;
preloaderImg = null;
});
A bit longer with nice opacity transition:
更长一点的不透明度过渡:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
let bgElement = document.querySelector(".bg-lazy");
bgElement.classList.add("bg-loading");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
preloaderImg.addEventListener('load', (event) => {
bgElement.classList.remove("bg-loading");
bgElement.style.backgroundImage = `url(${imageUrl})`;
preloaderImg = null;
});
.bg-lazy {
height: 100vh;
width: 100vw;
transition: opacity 1s ease-out;
}
.bg-loading {
opacity: 0;
}
<div class="bg-lazy"></div>
回答by Paperjuice
I've located a solution that worked better for me, and which has the advantage of being usable with several images (case not illustrated in this example).
我找到了一个更适合我的解决方案,它的优点是可用于多个图像(本示例中未说明的情况)。
From @adeneo's answer on this question:
来自@adeneo 对这个问题的回答:
If you have an element with a background image, like this
<div id="test" style="background-image: url(link/to/image.png)"><div>
You can wait for the background to load by getting the image URL and using it for an image object in javascript with an onload handler
var src = $('#test').css('background-image'); var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,''); var img = new Image(); img.onload = function() { alert('image loaded'); } img.src = url; if (img.complete) img.onload();
如果你有一个带有背景图片的元素,像这样
<div id="test" style="background-image: url(link/to/image.png)"><div>
您可以通过获取图像 URL 并将其用于带有 onload 处理程序的 javascript 中的图像对象来等待背景加载
var src = $('#test').css('background-image'); var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,''); var img = new Image(); img.onload = function() { alert('image loaded'); } img.src = url; if (img.complete) img.onload();
回答by Gino
I did a pure javascript hack to make this possible.
我做了一个纯 javascript hack 来使这成为可能。
<div class="my_background_image" style="background-image: url(broken-image.jpg)">
<img class="image_error" src="broken-image.jpg" onerror="this.parentElement.style.display='none';">
</div>
Or
或者
onerror="this.parentElement.backgroundImage = "url('image_placeHolder.png')";
css:
css:
.image_error {
display: none;
}
回答by yazabara
https://github.com/alexanderdickson/waitForImages
https://github.com/alexanderdickson/waitForImages
$('selector').waitForImages({
finished: function() {
// ...
},
each: function() {
// ...
},
waitForAll: true
});