How many $(document).ready() should I have in my code? Currently I have way too many, around 10+. Should I combine everything into one $(document).ready()? What are some cases where I should have more than one?
If there’s no duplicate code or functions, why bother? It’s not inherently wrong, but you could organize it better. The performance is slightly affected, not a biggie. If my code is modular and I have separate files, I write functions then initialize them once at the end: $(document).ready(function() { functionA(); functionB(); });
Completely depends on the structure of your code. With modern browsers though, you should probably be setting up much more specific event listeners within and outside of a single ready.
You can use an IIFE and use none if you like. I won’t hijack your post to tell you why x is better than y, but learning vanilla JavaScript will be more translatable to frameworks beyond jQuery.
Atlas said:
You can use an IIFE and use none if you like. I won’t hijack your post to tell you why x is better than y, but learning vanilla JavaScript will be more translatable to frameworks beyond jQuery.
No, jQuery is bad.
@Farrell
jQuery isn’t bad; many of its features were adopted into ECMAScript. It inspired modern frontend web development.
You should have none if you use type="module"
or async
or defer
. Check MDN for more.
Jess said:
You should have none if you usetype="module"
orasync
ordefer
. Check MDN for more.
async doesn’t guarantee it runs after the DOM is loaded. Type module or defer is the way.
Having that many suggests you might be copy-pasting code. One is enough for readability and maintainability.
Keir said:
Having that many suggests you might be copy-pasting code. One is enough for readability and maintainability.
Counter-argument: Having each piece of code self-contained increases maintainability because concerns are localized.
Short answer: it doesn’t matter much, but try to keep one for easier maintenance. Long answer: Use vanilla JS instead of jQuery when possible.
Combine them into one for clarity and efficiency unless separate ones are necessary for modular scripts.
Zero. There’s no reason for jQuery in 2024.
Bryn said:
Zero. There’s no reason for jQuery in 2024.
Don’t lib shame him. If they are a beginner, there’s nothing wrong with learning a bit of jQuery.
As many as it takes and no more. There’s nothing inherently wrong with waiting until the document is ready.
You should try to condense all the document.ready calls down into one. Having multiple makes it hard to follow when certain logic executes.
I argue for none. Convert dependent code into custom elements. This lets you start calculating before the document is ready.
You should have as few as possible, ideally zero if the logic is modularized correctly.
Probably none. It’s better to use defer
for scripts, which means you don’t need $(document).ready()
.
- Just use type=module or defer on the script tag.