What is the proper way to run code after page has done loading
I have page X.
in X, i put in the head tag, a script tag. the script needs to scan the body once the 开发者_JS百科body has done rendering.
I tried jQuery.ready() but it is not called! Can it be that the DOM is ready before the script is starting to run? what can I do?
thanks
jQuery.ready()
isn't a function (well, not the handler you want anyway), what you want is jQuery(document).ready()
, like this:
jQuery(document).ready(function() {
alert("DOM is ready!");
});
Or, the shorter form:
jQuery(function() {
alert("DOM is ready!");
});
Did you try calling ready like this:
<script type="text/javascript">
$(document).ready(function() {
//do things..
});
</script>
You may need to define what you mean by "done loading." The .ready()
function in jQuery, which is most often properly called as $(document).ready(handler);
, should indeed be invoked as soon as the DOM is finished loading. (If it's not being invoked, I suspect there's an error in your code or jQuery isn't loaded.)
However, there is often an intuitive confusion between the DOM being loaded and the "page" being loaded. The former is all jQuery really cares (or knows) about, and is not dependent on loading external content referenced by the DOM (such as images, style sheets, etc.).
According to this documentation, all three of the following syntaxes are equivalent:
* $(document).ready(handler)
* $().ready(handler) (this is not recommended)
* $(handler)
And this code provides a simple example:
<!DOCTYPE html>
<html>
<head>
<style>p { color:red; }</style>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$(document).ready(function () {
$("p").text("The DOM is now loaded and can be manipulated.");
});
</script>
</head>
<body>
<p>Not loaded yet.</p>
</body>
</html>
精彩评论