Calling $(document).ready multiple times with jQuery
Posted September 11th, 2009 in Javascript
jQuery's $(document).ready() function runs the code within that function after the DOM is loaded (I've written about this previously here). Something I haven't needed to do before, but was wondering if it's possible, is to use $(document).ready() more than once.
Calling $(document).ready() multiple times
The answer is that yes, it can be called multiple times. For example, you might have several Javascript library files and each of them may need to do something after the DOM has loaded. You could then easily put a $(document).ready() into each of them and they will all be run when the DOM's loaded.
To check this works I created the following page:
<html>
<head>
<script language="javascript" src="/js/jquery-1.3.2.min.js"></script>
<script language="javascript" src="/js/test1.js"></script>
<script language="javascript" src="/js/test2.js"></script>
</head>
<body>
</body>
</html>
test1.js contained the following:
$(document).ready(function() {
alert("1");
});
test2.js contained the following:
$(document).ready(function() {
alert("2");
});
Sure enough, I got two alert dialogs with the text "1" and then "2".
Related posts:
- jQuery Animated Information Box (Tuesday, September 8th 2009)
- Running a function with jQuery when the window is resized (Tuesday, August 25th 2009)
- Attaching an event to an element with jQuery (Tuesday, February 24th 2009)
- jQuery's document ready initialization (Friday, February 20th 2009)
- Loading content with jQuery AJAX (Wednesday, January 14th 2009)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)

Comments
blog comments powered by Disqus