Possible Duplicate:
JQuery - multiple $(document).ready …?
I have my JS code that is using jQuery within the jQuery Document Ready IE:
$(function() {
});
I am running multiple jQuery scripts on the page and all are contained within one $(function() { });
is there any reason I should break the scripts into multiple ready handlers? IE:
$(function() {
// First Script
});
$(function() {
// Second Script
});
//etc.
or is it okay to have multplie scripts within one? IE:
$(function() {
// First Script
//Second Script
//etc.
});
I assume one is just fine but I want to ensure there are no reasons I should use multiple ones.
You could have multiple document.ready
handlers in your script(s), jQuery will merge them into a single one before executing anyway. But it's really not necessary to have many document.ready handlers. One is enough. And if you put your scripts always at the end of your DOM, just before the closing </body>
tag you don't need to use any document.ready handlers.
For example:
<html>
<head>
<title></title>
... your CSS references come here
</head>
<body>
... the markup of the body comes here ...
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// you don't need to use any document.ready handlers here =>
// you could directly write your scripts inline or reference them
// as external resources. At this stage the DOM will be ready
</script>
</body>
</html>
It makes absolutely no difference with regards to how it works.
However, it can be useful for organision.
On the other hand, it means more jQuery has to run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With