Quickly understanding the jQuery Document Ready – $(document).ready() method

Quickly understanding the jQuery Document Ready – $(document).ready() method

The jQuery Document Ready is an event that executes JavaScript or jQuery code only after the HTML document has been completely loaded and its DOM (Document Object Model) has been created. In simple words, it ensures that all HTML elements are available before jQuery tries to access or manipulate them.

$(document).ready(function() {
    alert('DOM is Ready');
});

We can also use the shorthand $() for $(document).ready():

// Shorthand for $( document ).ready()
$(function() {
    alert('DOM is Ready');
});

What does “DOM Ready” mean?

When a browser loads a web page, it does not show everything at once. It works through the page in stages:

  1. The browser downloads the HTML and reads it from top to bottom.
  2. While reading, it builds the DOM (Document Object Model), a tree of all the HTML elements on the page, such as <button>, <div> and <p>.
  3. Once the whole HTML is parsed and the DOM tree is complete, the browser fires the DOMContentLoaded event. This is the moment jQuery calls “DOM ready”.
  4. The browser keeps downloading images, stylesheets and iframes. When all of them have finished, it fires the load event.

The $(document).ready() method runs your code at step 3. At that point every HTML element exists and can be selected and changed safely, and you do not have to wait for the images to finish loading.

Why is this important?

jQuery can only work with elements that already exist in the DOM. If your script runs before the browser has reached a particular element, then selectors like $(“#myButton”) find nothing, and any code that depends on them silently fails. Wrapping your code in $(document).ready() removes this problem, because the code waits until the DOM is complete.

Do you want to find one or more HTML element based on some condition? Then this tutorial is meant for you – jQuery Find Method – The Complete Tutorial for Programmers

Example of a Button Click

This example shows how to attach a click event handler to a button using jQuery. The handler is placed inside the $(document).ready() method, so it runs only after the DOM has fully loaded.

$(document).ready(function(){
    $("button").click(function(){
       alert('Button is Clicked');
    });
});

Note – In the above code, if you do not place the button click event inside the document ready function, then your code will not execute.

Therefore place all your codes inside jQuery Document Ready function.

Changing the color, font, padding, margin or any other CSS property of an HTML element can be easily done by using the jQuery CSS method

$(document).ready() vs $(window).on(“load”)

These two are often confused because both run code after the page has loaded. The difference is when they run. As explained above, the browser fires DOMContentLoaded first, when the DOM is built, and the load event later, when every image, stylesheet and iframe has finished downloading.

$(document).ready()$(window).on(“load”)
Fires whenThe DOM is fully builtThe whole page and all its resources are loaded
Waits for images and CSS?NoYes
Browser eventDOMContentLoadedload
SpeedEarlier, so the page feels responsive soonerLater, after the slowest image finishes
Multiple handlers allowed?Yes, they run in the order they were addedYes, they run in the order they were added
Typical useAttaching events, selecting and changing elementsCode that needs image sizes, or that depends on all resources

Seeing the difference in code

$(document).ready(function () {
    console.log("1. DOM is ready");
});

$(window).on("load", function () {
    console.log("2. Page fully loaded (images, CSS, etc.)");
});

Open the browser console and you will always see message 1 first. On a page with large images, there can be a noticeable gap before message 2 appears.

Which one should I use?

Use $(document).ready() for almost everything, such as binding click events, reading form values or adding and removing elements. Use $(window).on(“load”) only when your code really depends on resources being fully loaded. A common example is reading the width and height of an image, which is not known until the image has downloaded.

What happens without document ready?

The best way to understand why $(document).ready() matters is to see what goes wrong without it. Here is a page where the jQuery code sits in the <head>, before the button exists.

The wrong way: no document ready

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        // The browser has NOT reached the button yet
        console.log("Buttons found: " + $("#btnSave").length);

        $("#btnSave").on("click", function () {
            console.log("Button is clicked");
        });
    </script>
</head>
<body>
    <button id="btnSave">Save</button>
</body>
</html>

Open the console and you will see:

Buttons found: 0

Now click the button and nothing is logged. There is no error either, which makes this bug confusing for beginners.

Why does it fail?

The browser reads the page from top to bottom. When it runs the script in the <head>, the <button> further down has not been parsed, so it is not in the DOM yet. The selector $(“#btnSave”) returns an empty jQuery object, and calling .on(“click”, …) on an empty object does nothing. The code does run, but it attaches the click handler to zero elements.

The right way: with document ready

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        $(document).ready(function () {
            console.log("Buttons found: " + $("#btnSave").length);

            $("#btnSave").on("click", function () {
                console.log("Button is clicked");
            });
        });
    </script>
</head>
<body>
    <button id="btnSave">Save</button>
</body>
</html>

The console now shows:

Buttons found: 1

Clicking the button logs Button is clicked. The only change is the $(document).ready() wrapper. It delays the code until the DOM is complete, so the button exists when the selector runs.

Tip: If a jQuery event is not firing, check .length on your selector first. If it is 0, jQuery did not find the element, and timing is one of the most common causes.

Do you always need document ready?

Many tutorials say you must always put all your jQuery code inside $(document).ready(). That is a good habit, but it is not a strict rule. What matters is that your code runs after the elements it uses exist in the DOM. There are a few ways to guarantee that.

1. Place the script at the end of the body

If your script is the last thing before </body>, the browser has already parsed every element above it, so the DOM is ready when your code runs.

<body>
    <button id="btnSave">Save</button>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        // Safe without document ready: the button is already in the DOM
        $("#btnSave").on("click", function () {
            console.log("Button is clicked");
        });
    </script>
</body>

2. Use the defer attribute

A script with the defer attribute is downloaded while the HTML is being parsed, but it only runs after parsing is finished. Deferred scripts run in the order they appear, so jQuery must also be deferred and listed before your own file.

<head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" defer></script>
    <script src="/js/site.js" defer></script>
</head>

Note that defer only works on external scripts that have a src. It has no effect on inline <script> blocks.

So should I still use document ready?

Yes, in most cases. It costs almost nothing, and it keeps your code safe if someone later moves the script tag, for example from the bottom of the page to the <head>. A good rule is:

  • Script in the <head> without defer: use document ready.
  • Script at the end of <body> or loaded with defer: document ready is optional.

Document ready does not cover elements added later

This is a common misunderstanding. $(document).ready() only guarantees that the elements already in the HTML exist. It does not help with elements that are created afterwards, for example through AJAX, .append() or a template.

$(document).ready(function () {
    // Attached only to buttons that exist right now
    $(".btn-delete").on("click", function () {
        console.log("Deleted");
    });

    // A button added later does NOT get the handler above
    $("#list").append('<button class="btn-delete">Delete</button>');
});

To handle clicks on elements that do not exist yet, use event delegation. Attach the handler to a parent that already exists and give .on() a selector for the child:

$(document).ready(function () {
    // Works for current and future .btn-delete buttons
    $("#list").on("click", ".btn-delete", function () {
        console.log("Deleted");
    });

    $("#list").append('<button class="btn-delete">Delete</button>');
});

Here the handler is bound to #list, which exists at DOM ready. When a click happens on a .btn-delete inside it, jQuery runs the function, even if that button was added later.

Common mistakes with $(document).ready()

These are the problems beginners run into most often. Each one comes with the error you will see in the browser console (press F12 to open it) and the fix.

Mistake 1: Using jQuery before the library has loaded

<script>
    $(document).ready(function () {   // ReferenceError: $ is not defined
        console.log("Ready");
    });
</script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

The browser runs scripts in the order it meets them. Here your code runs before jQuery exists, so the browser does not know what $ is. Always load the jQuery library first:

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
    $(document).ready(function () {
        console.log("Ready");
    });
</script>

The same error appears if the jQuery file fails to download (a wrong path, a blocked CDN or no internet connection). Check the Network tab in the developer tools to confirm the file loaded.

Be careful with defer too. A deferred jQuery file runs only after the page is parsed, so an inline script that uses $ will run too early. Either defer both scripts as external files, or do not defer jQuery.

Mistake 2: Loading plugins before jQuery

<script src="/js/jquery.datepicker.js"></script>   <!-- plugin first: wrong -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>
    $(document).ready(function () {
        $("#dob").datepicker();   // TypeError: $(...).datepicker is not a function
    });
</script>

A jQuery plugin adds its methods to jQuery when it loads. If jQuery is not there yet, the plugin cannot register itself. The correct order is: jQuery, then plugins, then your own code.

Mistake 3: Loading jQuery twice

Adding the jQuery file a second time, often because a layout page and a view page both include it, replaces the first copy. Any plugins that were attached to the first copy are lost, and you get errors such as is not a function even though the plugin file is on the page. Include jQuery only once.

Mistake 4: Expecting variables and functions inside ready to be available outside

<button onclick="saveData()">Save</button>

<script>
    $(document).ready(function () {
        function saveData() {
            console.log("Saved");
        }
    });
</script>

Clicking the button gives Uncaught ReferenceError: saveData is not defined. The function is declared inside the ready callback, so it exists only inside that callback. The inline onclick looks for it in the global scope and cannot find it.

There are two fixes. The better one is to bind the event in jQuery and drop the inline attribute:

<button id="btnSave">Save</button>

<script>
    $(document).ready(function () {
        $("#btnSave").on("click", function () {
            console.log("Saved");
        });
    });
</script>

The other is to declare the function outside the ready block so that it is global. This works, but it is less tidy.

Mistake 5: Another library is using the $ symbol

Some libraries, such as Prototype, also use $. When they are loaded together, $ may not mean jQuery any more. Use the full name jQuery instead, and pass $ into the callback so you can still write short code inside it:

jQuery(document).ready(function ($) {
    // Inside this function, $ always means jQuery
    $("#btnSave").on("click", function () {
        console.log("Saved");
    });
});

If you need to give the $ symbol back to the other library completely, call jQuery.noConflict() after loading jQuery.

Mistake 6: A wrong selector, which fails silently

$(document).ready(function () {
    $(".btnSave").on("click", function () {   // the element has id="btnSave", not a class
        console.log("Saved");
    });
});

jQuery does not complain when a selector matches nothing. The handler is simply attached to zero elements. The usual causes are using . where you needed # (or the reverse), a typo in the id, or a different spelling or case. As shown earlier in this tutorial, check the length of the result first:

console.log($("#btnSave").length);   // 0 means jQuery found nothing

Quick checklist when your code does not run

  1. Open the console (F12) and read the first error message.
  2. Is jQuery loaded once, and before your code and your plugins?
  3. Is your code inside $(document).ready() (or is the script at the end of the body, or deferred)?
  4. Does $(“your-selector”).length return 1 or more?
  5. Are you using functions or variables from outside the ready block, or the other way round?

The link to download the source codes is given below:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate