If you’ve been developing with jQuery for any length of time you’ll have seen or even be using
There are a few reasons why you’d use
$(document).ready() in your scripts:
- You need to make sure the page is fully loaded before your script executes
- You don’t have control over where your script gets loaded
- You’re developing some jQuery-specific thing that you’re not sure how someone else will use
I only think the first two are valid. Of course before I go any further I have to make a quick disclaimer: there are no absolutes in programming and this is a generalization but let’s not focus on the cases where this doesn’t apply. Let’s focus on where this idea is true and correct so maybe in the future it’ll help you or someone you know out a little.
Optimizing for perceived page load times
So what’s this got to do with
$(document).ready() becomes useless. Well, not useless but definitely redundant. What
$(document).ready() does is check to make sure that the entire page has loaded before your script executes. If you load your scripts last then that’s a given and you don’t need to worry about it.
When should I use it?
Use it when you have no control over the markup. Wordpress plugins and themes come to mind first. With Wordpress, even if you write your own theme the way WP loads scripts and plugins could make it necessary. Should you use it in jQuery plugins? It’s probably safer to use it than not.
Why do we do what we do?
Every now and then I catch myself writing code because that’s just how I’ve always done it. Not because it needed to be there or because I knew what it did. I just saw it written that way or someone told me that’s how it’s supposed to be written and I just made it a habit to it. As I’ve grown over the years I don’t do this anymore. If you’re writing code that you don’t understand you should go back and learn about it. If you don’t, you might just end up doing something like, say, writing