The traditional mechanism for registering event handlers through JavaScript (ratherthan adding handler attributes right in HTML) is to assign a function to the DOMelement's corresponding attribute. For example, suppose we had defined the function:
function doStuff() {
// Perform a task...
}
We could then either assign it within our HTML markup:
<body οnlοad="doStuff();">
Or, we could assign it from within JavaScript code:
window.onload = doStuff;
Both of these approaches will cause the function to execute when the page is loaded.The advantage of the second is that the behavior is more cleanly separated fromthe markup.
function doStuff() {
// Perform a task...
}
<body οnlοad="doStuff();">
window.onload = doStuff;
Note here, that when we assign a function as a handler, we usethe function name but omit the trailing parentheses. With theparentheses, the function is called immediately; without, the namesimply identifies, or referencesthe function, and can be used tocall it later.
function doOtherStuff() {
// Perform another task...
}
We could then attempt to assign this function to run on page load:
window.onload = doOtherStuff;
However, this assignment trumps the first one. The .onloadattribute can only storeone function reference at a time: so we can't add this to the existing behavior.
function doOtherStuff() {
// Perform another task...
}
window.onload = doOtherStuff;
To be fair, jQuery doesn't have a monopoly on workarounds to thisissue. We can write a JavaScript function that forms a new functionthat calls the existing onloadhandler, then calls a passed-inhandler. This approach avoids conflicts between rival handlers like$(document).ready()does, but lacks some of the other benefitswe have discussed. In modern browsers, including Internet Explorer9, the DOMContentLoadedevent can be triggered with the W3Cstandard document.addEventListener()method. However,if we need to support older browsers as well, jQuery handles theinconsistencies that these browsers present so that we don't have to.
公平的说,jquery并不是仅有的可以在工作区中解决这件事的方法。我们可以写一个js函数,用它来组织一个新函数,先让他调用已在的onload事件处理器,然后调用后来的处理器。这种方法像$(document).ready()一样避免了两个相竞争的处理器之间的冲突,但是缺少一些我们讨论过的其他好处。在现在浏览器中,包括IE9,DOMContentLoader事件可以使用W3C标准的document.addEventListener()方法来触发。然而,如果我们也需要支持早期的浏览器,jquery可以处理这些浏览器呈现的不同,这样我们就不需要去做了。