在设置图像对象的src之前是否需要设置onload函数? [英] Is it necessary to set onload function before setting src for an image object?

查看:100
本文介绍了在设置图像对象的src之前是否需要设置onload函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被告知,在设置图像对象的 src 之前,需要设置 onload 函数。我已经在此搜索



<我发现这个代码:

  var img = new Image(); 
img.src ='image.jpg';
img.onload = function(){
document.body.appendChild(img);
};

但大多数人认为 onload 应该是写在 src 之前,像这样:

  var img = new Image() ; 
img.onload = function(){
document.body.appendChild(img);
};
img.src ='image.jpg';

必须它是按这个顺序写的吗?是否有任何情况下,上面的代码会导致错误(如图像太大)?

如果任何人都可以给我看一些例子,我会很欣赏。

解决方案

只要给src赋值,图片就会加载。如果在达到onload之前加载,则onload不会触发。



为了支持所有实现,我强烈建议在设置src之前分配onload处理函数。



我的经验(21年以上的JS),你必须首先设置onload - 特别是在IE开始使用JS时甚至不支持图像对象的情况。



如果你解决缓存图片不能触发的问题,当您下次设置src以避免缓存时,添加 +?+ new Date()。getTime()。 >

以下是MDN中的示例,它也使用了我所建议的顺序

$ b从头开始创建一个图片 $ b>



$ b

另一个SO链接 image.onload在IE7中不会触发两次 a>


I was told it is necessary to set the onload function before setting src for an image object. I've searched in SO for this.

I found this code:

var img = new Image();
img.src = 'image.jpg';
img.onload = function () {
    document.body.appendChild(img);
};

But most people believe that onload should be written before src like this:

var img = new Image();
img.onload = function () {
    document.body.appendChild(img);
};
img.src = 'image.jpg';

MUST it be written in this order? Are there any cases when the above code will cause an error (like if an image is too big)?

If you anyone can show me some examples, I will be very appreciate.

解决方案

As soon as you assign the src a value, the image will load. If it loads before the onload is reached, your onload will not fire.

To support ALL implementations, I strongly suggest to assign the onload handler before setting the src.

It is my experience (21+ years of JS) that you MUST set onload first - especially in IE which did not even support the image object when I started with JS.

If you get issues about the cached image not firing, add +"?"+new Date().getTime() when you set the src next time to avoid cache.

Here is the example from MDN which also uses the order I have suggested

Creating an image from scratch

Another SO link image.onload not firing twice in IE7

这篇关于在设置图像对象的src之前是否需要设置onload函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆