window.onload 、body.onload 以及 jQuery 等dom加载完成后执行脚本的区别

1.关于window.onload 和 body.onload 的区别

   当我们将onload 事件写在body元素上时,真正执行的其实是window对象的onload事件。因素HTMl页面中没有window标题,所以就写在body元素上了。

The onload attribute of the body object sets an onload event handler for the window. This technique of calling the window onload event through the bodyobject is overridden by any other means of invoking the window onload event, provided the handlers are in the same script language.

摘录自:http://technet.microsoft.com/zh-cn/subscriptions/index/cc197055(v%3Dvs.85).aspx

相关阅读:

defer,一个设计时可用的属性:
     在解决以下的问题,当然后可以在body元素的onload事件中写代码,当对于script来说,还可以为脚本添加一个名为defer的属性,使JavaScript脚本在“整个页面加载完成”后才执行。像上面的代码,如果写成以下的样子,则会被正确的执行。

 1 <html>
 2 <head>
 3       <script type="text/javascript" defer="true">
 4            var obj = document.getElementById("div1");
 5            obj.innerText = "This is my test defer attribute";
 6       </script>
 7 </head>
 8      <body>
 9             <div id="div1"></div>
10       </body>
11 </html>

     对于这个属性,微软有以下解释:

     Using the attribute at design time can improve the download performance of a page because the browser does not need to parse and execute the script and can continue downloading and parsing the page instead.

     所以这个说这个属性真正使用的地方并不会多。不过这有助于我们理解HTMl页面是如何加载到浏览器的。

原文地址:http://hi.baidu.com/arjsyy/item/94894ca86c34c49b1410732e

      可能你也碰到过这种情况,就是在js的代码中用了window.onload后,可能会影响到body中的onload事件。你可以全写在body 中,也可以全放到window.onload中,但是这样并不是很方便,有时我们需要两个同时用到。这时就要用window.attachEvent和 window.addEventListener来解决一下。

下面是一个解决方法。至于attachEvent和addEventListener的用法,可以自己Google或百度一下。

1 if (document.all)
2 {
3       window.attachEvent('onload',函数名)//IE中
4 }
5 else
6 {
7    window.addEventListener('load',函数名,false);//firefox
8 }

  原文地址:http://blog.sina.com.cn/s/blog_4be585ca01000akh.html

  推荐一篇博客:http://blog.csdn.net/john2522/article/details/7885453

posted @ 2014-04-26 23:52  未来动力  阅读(1427)  评论(0编辑  收藏  举报