There are two alternatives to document ready that are a bit easier to type
Most JavaScript programmers are familiar with jQuery’s document ready function. There is no doubt that it is a very helpful way to wrap your JavaScript with a cross-browser compatible function that will not run until the document has achieved a “ready” state. While the syntax is fairly simple, there are two slightly less verbose alternatives to the exact same functionality.
Example # 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Three variations on the jQuery document ready function</title> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> $(document).ready(function(){ console.log("the document is ready") }); </script> </head> <body> </body> </html> |
In Example # 1, we have the standard syntax for the jQuery document ready function.
Example # 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Three variations on the jQuery document ready function</title> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> $(function(){ console.log("the document is ready") }); </script> </head> <body> </body> </html> |
In Example # 2, we omit the “document / ready” portion of the equation, and simply insert our function in the following expression $().
Example # 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Three variations on the jQuery document ready function</title> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> $().ready(function(){ console.log("the document is ready") }); </script> </head> <body> </body> </html> |
In Example # 3, we chain a jQuery ready() function to the return value of the jQuery object: $().ready(). So, when the jQuery object is ready, so is our code.
Summary
There is no doubt that the jQuery document .ready() function is super-useful. There is however, more than one way to invoke this functionality.
Helpful links for the jQuery document .ready() function
http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
http://rpheath.com/posts/403-jquery-shorthand-for-document-ready
http://think2loud.com/653-jquery-document-ready-howto/