I'm on a bit of a roll with my jQuery posts, so let's keep it going! Today I want to share a quick tip about the ready() method, which lets you wait until the Document Object Model (DOM) is ready for your JavaScript code to execute. Specifically, I want to talk about the modern recommended syntax.

I usually see the ready() method written the old-school way, like this:

$(document).ready(function() {
// The document is ready!

But the following is actually the recommended syntax nowadays:

$(function() {
// The document is ready!

The jQuery docs explain why:

jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example, the third syntax works with "document" which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.

There's plenty more info in the docs for the ready() method, so check them out if you'd like to know more about the method in general.