jQuery的官方网站的解释如下:
“While JavaScript provides theloadevent for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to.ready()is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
当页面DOM 元素全部加载完毕后就执行.ready()。
如果在.ready()执行之前有javascript代码存在,那么javascript将怎么执行呢?
答案是先执行.ready()之前的javascript代码,然后执行.ready()。
写个example
<!DOCTYPE html>
<html>
<head></head>
<body>
<span>This page is shown to understand '$(document).ready()' in jQuery. <br /><span>
<p>
If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS...<br /><br />
</p>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
document.write('The JS is doing sth after DOM loaded and before executing $(document).ready()...<br /><br />');
//alert('The JS is doing sth after DOM loaded and before executing $(document).ready()...');
document.write('DOM is loaded and $(document).ready() will now be executed!<br /><br />');
//alert('DOM is loaded and $(document).ready() will now be executed!');
$(document).ready(function () {
$(document.body).append("$(document).ready() is now been executed!!!<br /><br />");
//alert("$(document).ready() is now been executed!!!");
});
</script>
</body>
</html>
执行完页面打印出来的顺序是:
This page is shown to understand '$(document).ready()' in jQuery. If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS... The JS is doing sth after DOM loaded and before executing $(document).ready()... DOM is loaded and $(document).ready() will now be executed! $(document).ready() is now been executed!!!
浙公网安备 33010602011771号