One more great thing about $(document).ready() that I didn't mention
in my previous tutorial is that you can use it more than once. In fact,
if you don't care at all about keeping your code small, you could litter
your JavaScript file with them.
It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain free.
You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready(). So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so:
You could also do something like this inside a single .js file:
A final note: Here's an excellent tip for shrinking your code. There's a shortcut available for $(document).ready(), you can write $(function(){ ... }) instead, like so:
A function passed as an argument to the jQuery constructor is bound to the document ready event. This way you can have even shorter code!
It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain free.
You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready(). So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so:
<script src="/scripts/jquery.js"></script> <script src="/scripts/common.js"></script> <script src="/scripts/homepage.js"></script>
You could also do something like this inside a single .js file:
$(document).ready(function() { // some code here }); $(document).ready(function() { // other code here });
A final note: Here's an excellent tip for shrinking your code. There's a shortcut available for $(document).ready(), you can write $(function(){ ... }) instead, like so:
$(function() { // do something on document ready });
A function passed as an argument to the jQuery constructor is bound to the document ready event. This way you can have even shorter code!
Comments
Post a Comment