---
title: "onload事件和window，document，body的研究"
author: "wfsheep"
date: "2014-10-28T13:31:00Z"
tags: []
slug: "onload-window-document-body"
draft: false
lastmod: "2015-03-05T13:15:40Z"
id: 2189018
url: "https://wfsheep.iteye.com/blog/2189018"
---

今天在工作中用到了onload事件，发现了一些有趣的事情，比如一般来说，如果我们需要给一个DOM结构绑定一个事件，我们一般会采用如下方法（以Window对象为例）：

【现象】

```
	window.onload = function() {
		console.log('<span style="font-family: Arial, Helvetica, sans-serif;">window.onload</span><span style="font-family: Arial, Helvetica, sans-serif;">');</span>
	};
   
        window.addEventListener && window.addEventListener("load", function() {
		console.log('window.addEvent');
	});
```

执行这两个方法，可以看到如下截图：

![](http://img.blog.csdn.net/20141028103530841?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2ZzaGVlcA=%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)

说明，这两个方法都被触发了，在这一点上IE表现也是一致的。

接下来我们来试试document对象

```
	document.onload = function() {
		console.log('document.onload');
	};
   
        window.addEventListener && document.addEventListener("load", function() {
		console.log('<span style="font-family:Arial, Helvetica, sans-serif;">document</span>.addEvent');
	});
	
	window.attachEvent && document.attachEvent('onload', function() {
		console.log('document.attachEvent');
	});
```

执行后发现，document的onload事件无论是哪种方式都不会触发。

再接下来，我们来试试body对象

```
	document.body.onload = function() {
		console.log('body.onload');
	};
	
	window.addEventListener && document.body.addEventListener("load", function() {
		console.log('body.addEvent');
	});
	
	window.attachEvent && document.body.attachEvent('onload', function() {
		console.log('body.attachEvent');
	});
```

结果如下图：

![](http://img.blog.csdn.net/20141028110904851?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2ZzaGVlcA=%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)

可以看到，说明通过这种写法只有onload方式绑定的被触发了。

还有更好玩的，当同时给body和window使用onload方法时，只有window的onload方法触发

具体代码如下：

```
	document.body.onload = function() {
		console.log('body.onload');
	};
	
	window.onload = function() {
		console.log('window.onload');
	}
```

执行结果如：

![](http://img.blog.csdn.net/20141028131758125?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2ZzaGVlcA=%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)  
【结论】

所以总结如下：  
1、onload和addEventListener当使用在window上的时候都触发

2、当使用在document时，都不触发

3、当使用在body上时，只有onload触发

4、当body和window同时使用onload方法时，body的方法会被吃掉。

【深入研究】

这里的研究主要是参看了w3c草案中的一些说明，怕翻译不好，贴出原文，貌似load事件和其他的有很多不同，

6.1.6.3*Event firing*

Certain operations and methods are defined as firing events on elements. For example, the`click()`method on the`HTMLElement`interface is defined as firing a`click`event on the element.[\[DOMEVENTS\]](http://www.w3.org/TR/2011/WD-html5-20110525/references.html#refsDOMEVENTS)

Firing a simple event named`e`means that an event with the name`e`, which does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and which uses the`Event`interface, must be dispatched at the given target.

Firing a synthetic mouse event named`e`means that an event with the name`e`, which does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and which uses the`MouseEvent`interface, must be dispatched at the given target. The event object must have its`screenX`,`screenY`,`clientX`,`clientY`, and`button`attributes set to 0, its`ctrlKey`,`shiftKey`,`altKey`, and`metaKey`attributes set according to the current state of the key input device, if any (false for any keys that are not available), its`detail`attribute set to 1, and its`relatedTarget`attribute set to null. The`getModifierState()`method on the object must return values appropriately describing the state of the key input device at the time the event is created.

Firing a`click`eventmeans[firing a synthetic mouse event named`click`](http://www.w3.org/TR/2011/WD-html5-20110525/webappapis.html#fire-a-synthetic-mouse-event "fire  a synthetic mouse event"), which bubbles and is cancelable.

The default action of these events is to do nothing except where otherwise stated.

##### 6.1.6.4Events and the`Window`object

When an event is dispatched at a DOM node in a`Document`in a[browsing context](http://www.w3.org/TR/2011/WD-html5-20110525/browsers.html#browsing-context), if the event is not a`load`event, the user agent must also dispatch the event to the`Window`, as follows:

1. In the capture phase, the event must propagate to the`Window`object before propagating to any of the nodes, as if the`Window`object was the parent of the`Document`in the dispatch chain.
2. In the bubble phase, the event must propagate up to the`Window`object at the end of the phase, unless bubbling has been prevented, again as if the`Window`object was the parent of the`Document`in the dispatch chain

另外就是，在第6.1.6.2节中有详细描述window，document，body对象对各事件的支持，因为太长，就不贴出来了。

Ps：本文纯属个人研究，如有谬误，烦请指出，万分感谢。