简体   繁体   English

Javascript预加载-加载不一致

[英]Javascript preload - onload inconsistencies

What is the difference between 之间有什么区别

<img id="el" src="HD.jpg" onload="loadImage();">
function loadImage() {...}

and

<img id="el" src="HD.jpg">
document.getElementById('el').onload=loadImage();

?

Example 1 triggers the function when the image is fully loaded, example2 triggers it even before the first bit of image is loaded. 示例1在图像完全加载时触发该函数,而示例2甚至在图像的第一位加载之前触发该函数。 Isn't it supposed to be the same thing ? 是不是应该是同一回事?

The difference is hard to spot with a full speed internet access but obvious with a narrow one. 全速互联网访问很难发现差异,而窄速互联网则明显。

Notice that 注意

document.getElementById('el').src.onload=loadImage();

doesn't work either. 也不起作用。

Thanks 谢谢

edit: sorry for the approximative post title, don't hesitate to suggest a proper one. 编辑:对近似的职位感到抱歉,不要犹豫,建议一个合适的职位。

You are doing something quite different from what you think you're doing: you are assigning the value returned by loadImage to ..onload member of the img element. 您所做的事情与您认为的工作完全不同:您将loadImage返回的分配给img元素的..onload成员。

What actually happens is that when your script loads, it assigns the result of calling loadImage() function (this is why you see it run before any images), which is most likely undefined to img.onload handler, thereby disabling it. 实际发生的情况是,在脚本加载时,它会分配调用loadImage()函数的结果(这就是为什么您看到它在任何图像之前运行的原因)的原因,这很可能在img.onload处理函数中undefined ,因此将其禁用。

To do what you want, you need to assign a function to img.onload handler - for example - just wrap in another function: 要执行所需的操作,您需要为img.onload处理函数分配一个函数 -例如,只需包装另一个函数即可:

document.getElementById('el').src.onload = function() { loadImage(); };

or you can directly assign your function as a handler. 或者您可以直接将您的函数分配为处理程序。 It nicely illustrates why it didn't work before, although I wouldn't recomend it: 它很好地说明了为什么它以前不起作用,尽管我不建议这样做:

document.getElementById('el').src.onload = loadImage;

(note missing () ) (请注意缺少()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM