该$(document).ready(..)
方法试图解决的问题是页面的 javascript 代码执行与页面中的控件被绑定的时间之间的紧张关系。ready
一旦文档准备好并且 DOM 元素可用,该函数将触发,因此 javascript 代码可以对 DOM 做出合理的假设
最常见的例子是 javascript 代码相对于它试图操作的 DOM 元素的位置。考虑
<script>
$('#target').click(function() {
alert('It was clicked');
});
</script>
<div id="target">Click Me</div>
In this particular example the javascript will not function as intended. When the script block is entered the click
line is run and there currently is no DOM element with the id target
hence the handler binds to nothing. There is nothing really wrong with the code, it just had the unfortunate timing to run before the DOM element was created.
In this example the problem is obvious because the code and DOM element are visually paired together. In more complex web pages though the javascript is often in a completely separate file and has no visual guarantees about load ordering (nor should it). Using the $(document).ready(..)
abstraction removes the question of ordering as a potential source of problems and facilitates proper separation of concerns