Javascript 检查图像源已加载
我一直在尝试让它工作,但没有 100% 成功,基本上是尝试加载图像,如果源不存在,请尝试第二个图像,直到达到默认图像。
function topTenImages(){
var topTenDiv = document.getElementById('toptenimg');
var topTenImg = new Image();
var ac = "tryout";
var imageOrder = new Array(
"/images/codespec/banners/"+ac+"_topten.gif",
"/images/codespec/banners/"+ac+"_topten.jpg",
"/images/banners/default_topten.png",
"/images/banners/default_topten.jpg"
);
var errorCnt = 0;
topTenImg.src = domainResources+imageOrder[errorCnt];
topTenImg.onLoad = new function(){
if(!checkImage(topTenImg)){
if(errorCnt < imageOrder.length){
var io = imageOrder[++errorCnt];
topTenImg.src = domainResources+io;
}
}
}
topTenDiv.appendChild(topTenImg);
}
是的,我知道我们可以使用 php/perl/et al 来完成此服务器端,但我们正在尝试限制我们的传出标头,所以这似乎是最好的方法。 (欢迎替代方案)。我的另一个想法是将其包装在数组上的 for 循环中,并每次创建一个新对象。但这似乎更有意义。
谢谢, 心理
I've been trying to get this working, and not having 100% success, basically trying to load an image, if the source doesn't exist try a second image until it reaches a default one.
I have been trying the solution based on this question, however I am not using jQuery, so the accepted solution is no use to me, so trying the 2nd solution, which pretty much works, but doesn't seem to be (if that makes sense?). I can get it to test the second image we need, but then it doesn't seem to trigger the onload event again.
function topTenImages(){
var topTenDiv = document.getElementById('toptenimg');
var topTenImg = new Image();
var ac = "tryout";
var imageOrder = new Array(
"/images/codespec/banners/"+ac+"_topten.gif",
"/images/codespec/banners/"+ac+"_topten.jpg",
"/images/banners/default_topten.png",
"/images/banners/default_topten.jpg"
);
var errorCnt = 0;
topTenImg.src = domainResources+imageOrder[errorCnt];
topTenImg.onLoad = new function(){
if(!checkImage(topTenImg)){
if(errorCnt < imageOrder.length){
var io = imageOrder[++errorCnt];
topTenImg.src = domainResources+io;
}
}
}
topTenDiv.appendChild(topTenImg);
}
Yes I know that we could do this server side with php/perl/et al, but we are trying to limit our outgoing headers, so this seemed to be the best way of doing it. (Alternatives welcome). My other thought was to wrap it in a for loop on the array, and create a new object each time. But this seemed to make more sense.
Thanks,
Psy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该回答你的问题:
http://www.thefutureoftheweb.com/blog/image-onload-未被调用
你只需要先设置onLoad即可。希望这会起作用:
This should answer your question:
http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
You just need to set onLoad first. Hopefully that will work: