(4)事件处理——(4)网页上的多个脚本(Multiple scripts on one page)
function doOtherStuff() {// Perform another task...}我们可能企图让我们的函数在页面加载的时候就运行起来:
window.onload = doOtherStuff;然而这个绑定覆盖了第一个。.onload属性一次只能存储一个函数引用,因此我们不能把这个添加在已经存在的行为上。The $(document).ready()mechanism handles this situation gracefully. Each call to the method adds the new function to an internal queue of behaviors; when the page is loaded all of the functions will execute. The functions will run in the order in which they were registered.
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可以处理这些浏览器呈现的不同,这样我们就不需要去做了。