等待CSS中的背景图像完全加载 [英] Wait for background images in CSS to be fully loaded
问题描述
我有一个网络应用程序使用外部背景图片加载在外部CSS。现在,可以在图像完全呈现之前使用应用程序,创建奇怪的视觉效果。
I have a web app that uses external background images loaded in external CSS. Right now, it is possible to use the app before the images have fully rendered, creating weird visual effects.
如何停止脚本执行,直到图像完全加载?
How can I halt script execution until the images are fully loaded?
它可以使用普通的JavaScript或jQuery。因为图像被加载到外部CSS中,我阅读的正常触发器不工作。
It can use normal JavaScript or jQuery. Because the images are loaded in external CSS the normal triggers I have read about don't work.
推荐答案
具有背景图片,像这样
<div id="test" style="background-image: url(link/to/image.png)"><div>
您可以等待背景加载,方法是获取图片网址并将其用于图片对象带有onload处理程序的javascript
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();
这篇关于等待CSS中的背景图像完全加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!