Last updated on

Before you start tinkering with elements on a web page you need to wait until the DOM has been loaded. That’s where the jQuery document ready function comes in.

Waiting for the DOM

One of the more common tasks that you’ll need jQuery / JavaScript for is to manipulate elements on a page (the DOM).

You can start doing this straight away as soon as your browser has the first byte of data.

However, this might be unsafe as the DOM may not have fully loaded yet and you might be trying to access elements that haven’t flown through cyberspace yet!

That’s why we need to wait until the DOM has been assembled. Like trying to play with a Lego toy before it’s been completely built, we don’t want to jump the gun.

Document, ready!

In order to only execute our jQuery code when the DOM has been constructed we can use the document ready method provided directly from the jQuery library.

<script>
  $(document).ready(function(){
    console.log("It's safe now.");
  });
</script>

To explain, we’re basically using jQuery to select the document element (basically the entire DOM) and pass in an anonymous function to the ready method that contains the code that should be run once the page is fully loaded.

Simple enough?

Shorthand

You’ll be pleased to know that there is also a shortcut to doing this.

<script>
  $(function(){
    console.log("It's safe now.");
  });
</script>

So you can omit the document element and also the ready function and just pass in the anonymous function to the jQuery function.

That should save a couple of bytes of bandwidth within your code!

Conclusion

Using the document ready function ensures you are only working with elements that are actually there on your page.  Therefore it’s a good idea and good practice to write all of your jQuery code inside the document ready function.