jQuery: Document ready event

This entry is part 3 of 33 in the series jQuery Tutorial

In this simple jQuery program, we have a document ready event.

$(document).ready()

The $ tells us that document is a jQuery object and it accesses a jQuery method called ready().

This ready() method is a way to check that the document we are accessing has all its elements (h1, body, p, span etc) loaded.

For example, we need to ensure that <h1> is ready before changing the text wrapped inside the heading tags.

Ready() is only one of the jQuery methods and this method is associated with document object.

Its been said that this document ready method is so common that the jQuery team develops a shorter method to write it.

$(function(){})

Look also at how we update <h4> using a jQuery method.  This line here will execute after the document is fully loaded.

$('#demo').html('Document is ready and loaded');

 

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script>
        $(function () {
            $('#demo').html('Document is ready and loaded');
        });
    </script>
</head>
<body>
<h4 id='demo'>Document Not Ready</h4>
</body>
</html>
Try The Code

jQuery: Document.ready vs windows.load

This entry is part 4 of 33 in the series jQuery Tutorial

The ready() event occurs after the HTML document has been loaded, while the load() event occurs later, when all content (e.g. images) also has been loaded.

The load() event is a standard event in the DOM, while the ready() event is specific to jQuery.

The purpose of the ready() event is that it should occur as early as possible after the document has loaded, so that code that adds funcionality to the elements in the page doesn’t have to wait for all content to load.

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#doc').html('Document is ready and loaded');
        });

        $(window).load(function() {
            $('#win').html('Window is ready and loaded');
        });
    </script>
</head>
<body>
<h4 id='doc'>Document Not Ready</h4>
<iframe src="https://codecrawl.com"></iframe>
<h4 id='win'>Window Not Ready</h4>
</body>
</html>

Run the code above and you will find that document will get ready first.

As for window, it will be ready after codecrawl.com is loaded inside the frame.

Try The Code