The traditional mechanism for registering event handlers through JavaScript (rather than adding handler attributes right in HTML) is to assign a function to the DOM element'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 onload="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 from the markup.
function doStuff() { // Perform a task... }
<body onload="doStuff();">
window.onload = doStuff;
Note here, that when we assign a function as a handler, we use the function name but omit the trailing parentheses. With the parentheses, the function is called immediately; without, the name simply identifies, or referencesthe function, and can be used to call 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 store one 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 this issue. We can write a JavaScript function that forms a new function that calls the existing onloadhandler, then calls a
passed-in handler. This approach avoids conflicts between rival handlers like $(document).ready()does, but lacks some of the other benefits we have discussed. In modern browsers, including Internet Explorer 9, the DOMContentLoadedevent can be triggered with
the W3C standard document.addEventListener()method. However, if we need to support older browsers as well, jQuery handles the inconsistencies that these browsers present so that we don't have to.
公平的说,jquery并不是仅有的可以在工作区中解决这件事的方法。我们可以写一个js函数,用它来组织一个新函数,先让他调用已在的onload事件处理器,然后调用后来的处理器。这种方法像$(document).ready()一样避免了两个相竞争的处理器之间的冲突,但是缺少一些我们讨论过的其他好处。在现在浏览器中,包括IE9,DOMContentLoader事件可以使用W3C标准的document.addEventListener()方法来触发。然而,如果我们也需要支持早期的浏览器,jquery可以处理这些浏览器呈现的不同,这样我们就不需要去做了。