(4)事件处理——(4)网页上的多个脚本(Multiple scripts on one page)
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;
$(document).ready()机制很优雅的处理了这种场景。每一个调用的函数将会被添加一个函数到内部的行为队列中。当页面被加载后,所有的函数将会被执行。这些函数将会按照我们注册函数的顺序来执行。
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可以处理这些浏览器呈现的不同,这样我们就不需要去做了。