等待图像加载,然后执行所有其他代码 [英] Wait for images to load and then execute all other code
问题描述
好的,我对此一无所知.我确实在SO和google上阅读过有关此内容的信息,甚至还设置了预加载器(在SO上找到),但是我发现的所有插件/代码都对我没有帮助.
OK, I'm losing my mind over this. I did read here at SO and google about it, I even have the preloader set (found here on SO), but none of the plugins/code I found helped me.
我想要做的是:等到所有图像都被预加载,然后再执行所有其他javascript代码.就我而言,它可以(但不是必须)具有正在加载..."消息.
What I want to do is: wait until all images are preloaded and only then execute all other javascript code. As far as I'm concerned it can (but not a must) have a "loading..." message.
事实是,我的身体背景上有一个很大的图像,另外两个图像也更大,所以我想对其进行预加载,以便它们可以立即显示,而不会出现难看的加载"图像效果.
The fact is that I have a pretty big image in the body background and 2 other images which are also bigger, and so I would like to preload them so that then they would show instantly and would not have that ugly "loading" image effect.
这是我现在正在使用的,但是不好:
This is what I'm using now but it's not good:
$(document).ready(function()
{
preloadImages();
...some other code...
function preloadImages(){
imagePreloader([
'images/1.png',
'images/2.jpg',
'images/3.png',
]);
}
function imagePreloader(arrayOfImages) {
$(arrayOfImages).each(function(){
(new Image()).src = this;
});
}
}
我不知道,也许我应该在.ready()之外的某个地方调用此预加载器?或类似的东西,请帮忙...
I don't know, maybe I should call this preloader somewhere out of the .ready()? or sth like that, please help...
Btw, yes, I also read this post and I don't know why but .ready() works faster for me :(
好的,所以最后我使这件事起作用了.我的问题?我将等待的div设置为错误.现在这是我的代码:我有一个加载div,它显示在所有内容之上,然后在加载所有图像时(使用$(window).load(function(){...});如建议的那样,隐藏该div. /p>
Ok, so finally I got this thing to work. My problem? I was setting the waiting div wrong. This is my code now: I have the loading div which I show above everything and then when all images load (using $(window).load(function(){...}); as suggested I, hide that div.
<div id="loading">
<div id="waiting">
<img class="loadingGif" src="images/loading.gif">
</div>
</div>
#loading
{
background-size: 100%;
background-color:#000;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
z-index:999;
}
#waiting
{
margin-left: auto;
margin-right: auto;
position:absolute;
top: 39%;
left: 27.81%;
width: 45%;
height: 150px;
background-color: #FFF;
border: 12px solid #FF771C;
text-align: center;
}
我的jQuery代码是这样:
And my jQuery code is this:
$(window).load(function()
{
$('#loading').addClass('hidden');
...
}
推荐答案
除了尝试预加载外,您还可以在...上执行脚本
Instead of trying to preload, you could just execute your script on...
window.onload = function(){..}
要等到所有图像加载完毕后才能触发.
That doesn't fire until all images have been loaded.
这篇关于等待图像加载,然后执行所有其他代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!