$(document).ready()
has one purpose - to execute some code after the DOM has finished loading and is now ready for access or modification.
If your code is located before DOM elements such as in the <head>
tag or in the top or middle of the <body>
section before some DOM elements and that code does attempt to access the DOM upon first initialization, then it should be placed into a $(document).ready()
block so it will not execute before the DOM is ready or the ` tag should be moved.
If your code is in a <script>
tag within the <body>
that is after the DOM elements that it needs to access then your code does not need to be in a $(document).ready()
block.
Or, if your code is not called upon initialization (e.g. it's only called later upon other events) or your code does not access the DOM upon initialization, then that code does not need to be inside a $(document).ready()
block.
Though you obviously have jQuery available, you can read this answer for a more detailed description: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.
Having multiple $(document).ready()
blocks is just like registering multiple callbacks for an event. It's really no big deal. Each one just takes an extra couple function calls to setup and is an extra callback execution at execution time. If that's the cleanest way to write your code, then by all means use multiple $(document).ready()
blocks.
To summarize, put code into a $(document).ready()
block when:
- A specific block of code needs to access the DOM when it is first run and the code is located in a script tag that is placed before the end of the
<body>
tag or is placed before some DOM elements that it might need to access.
There is no need to put code into a $(document).ready()
block when:
- The part of the code that runs at first initialization does not access the DOM.
- The code is placed into a
<script>
tag that is after the DOM elements that it references.
- The
<script>
tag is marked defer
because this explicitly instructs the browser to delay the running of this script tag until after the DOM has been parsed.
Also, keep in mind that it does not matter where functions are declared. It only matters where the functions are called from. So, you can define as many functions as you want outside of $(document).ready()
. You just have to make sure that any functions that access the DOM are not called too soon.