Javascript - 等待图像加载 [英] Javascript - wait images to be loaded
问题描述
var l = false;
var l2 = false;
var imm = new Image();
imm.src = "b.png";
imm.onload = function(){
l = true;
}
var imm2 = new Image();
imm2.src = "c.png";
imm2.onload = function(){
l2 = true;
}
如果<$ c $,我怎么能告诉这个javascript启动一个函数c> l 和 l2
是真的吗?我应该设置一个循环来不断检查这两个变量吗?有没有更有效的方法?我不希望我的脚本在没有图像的情况下启动但是使用 .onload
我可以等待只加载一个图像而不是所有图像。谢谢你的帮助!
How can I tell this javascript to start a function only if l
and l2
are true? Should I set a loop which constantly check for these two variables? Is there any more efficient way? I don't want my script to start without images but with .onload
I can wait for just one image to be loaded and not all of them. Thanks for your help!
推荐答案
无需循环。你可以让他们调用一个函数来检查l和l2是否为真并执行你想要做的事情:
No need for loops. You could let them call a function that checks if l and l2 are true and perform the thing you want to do:
var onLoaded = function() {
if (l && l2) {
// do your stuff
}
}
imm.onload = function(){
l = true;
onLoaded(); // call to onLoaded
}
imm2.onload = function(){
l2 = true;
onLoaded(); // call to onLoaded
}
它基本上是一个简单的观察者模式。有一些jQuery插件,如 Radio.js ,可以为您封装。
It is basically a simpler form of the Observer Pattern. There are jQuery plugins such as Radio.js that encapsulate this for you.
这篇关于Javascript - 等待图像加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!