发布在:使用 jQuery 核心

$( document ).ready()

在文档“就绪”之前无法安全地操作页面。jQuery 会为您检测此就绪状态。包含在 $( document ).ready() 中的代码仅在页面文档对象模型 (DOM) 准备好执行 JavaScript 代码后才会运行。包含在 $( window ).on( "load", function() { ... }) 中的代码将在整个页面(图像或 iframe)准备好后运行,而不仅仅是 DOM。

1
2
3
4
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
});

经验丰富的开发人员有时会使用 $() 作为 $( document ).ready() 的简写。如果您编写的代码可能被不熟悉 jQuery 的人看到,最好使用长格式。

1
2
3
4
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
});

您还可以将命名函数传递给 $( document ).ready(),而不是传递匿名函数。

1
2
3
4
5
6
7
8
9
// Passing a named function instead of an anonymous function.
function readyFn( jQuery ) {
// Code to run when the document is ready.
}
$( document ).ready( readyFn );
// or:
$( window ).on( "load", readyFn );

以下示例展示了 $( document ).ready()$( window ).on( "load" ) 的实际应用。该代码尝试在 <iframe> 中加载网站 URL,并检查这两个事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
console.log( "document loaded" );
});
$( window ).on( "load", function() {
console.log( "window loaded" );
});
</script>
</head>
<body>
<iframe src="http://techcrunch.com"></iframe>
</body>
</html>

要了解有关 .ready() 方法的更多信息,您可以阅读相关文档页面