Are there any real advantages to using window.onload=function(){}; over onload=function(){}; ? I know window.onload looks more proper, but that's not a good reason for me to choose it, especially that it's longer/slower than onload.
After some time-consuming searches and tests, those 2 were the only 2 browser compatible methods, the tests (on relatively new Chrome/Firefox versions, and IE from 5.5 to 9) included:
window.onload // works in all tested browsers
onload // works in all tested browsers, faster than window.onload
document.onreadystatechange // works twice in some browsers, once in some others, could be confusing
window.onpageshow // works in chrome and firefox, not in IE
window.onreadystatechange // doesn't work
document.onload // doesn't work
document.onpageshow // doesn't work
window.document.onload // doesn't work
Run Code Online (Sandbox Code Playgroud)
I could find this article which is one of the most suited articles to my question:
http://perfectionkills.com/onloadfunction-considered-harmful/
It states that the strict mode of ECMA-262 5th edition ("use strict"; which I don't plan to use in my project) could finally cause some browser incompatibility to onload (ReferenceError in Firefox and Opera).
所以问题是:除了"use strict"之外,使用直接onload赋值是否有任何真正的缺点?一?我需要的信息不是一些无法解释的意见.
谢谢
注意:我在问这个问题之前做过搜索(看起来有点经典),我能找到的最接近的问题是关于window.onload vs <body onload ="">,window.onload的其他替代方法等.
编辑:我已经创建了这个测试用例onload vs window.onload,这证明了onload的速度有多快.我真的会去做这种微观优化,为什么不呢?它们有时可能很酷.
两者是相同的...当您单独调用 onload 时,javascript 会假定它是一个全局属性,即 window 对象的属性。所以基本上如果你没有明确指出它是 window.onload 那么 javascript 引擎会为你做这件事。
if (onload === window.onload) {
alert("it's the same"); //true
}
Run Code Online (Sandbox Code Playgroud)
因此,只要您不关心严格模式,现代浏览器就不会有任何问题。然而,使用完整的 window.onload 而不是仅仅使用 onload 被认为更好。如果不输入额外的 7 个字符,您不会获得太多好处。