Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery document.ready

I am a little confused with document.ready in jQuery.

When do you define javascript functions inside of $(document).ready() and when do you not?

Is it safe enough just to put all javascript code inside of $(document).ready()?

What happens when you don't do this?

For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?

Is it only going to cause problems if someone clicks on the element in the split second before the page has loaded? Or can it cause other problems?

like image 670
Dave31415 Avatar asked Mar 11 '12 18:03

Dave31415


People also ask

What is document ready in jQuery?

$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Does jQuery need document ready?

ready. If you've been developing with jQuery for any length of time you'll have seen or even be using $(document). ready() at the start of your JavaScript file.

Why We Write document ready in jQuery?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

What does document ready mean?

The document ready event signals that the DOM of the page is now ready, so you can manipulate it without worrying that parts of the DOM has not yet been created. The document ready event fires before all images etc. are loaded, but after the whole DOM itself is ready.


2 Answers

When do you define javascript functions inside of $(document).ready() and when do you not?

If the functions should be globally accessible (which might indicate bad design of your application), then you have to define them outside the ready handler.

Is it safe enough just to put all javascript code inside of $(document).ready()?

See above.

What happens when you don't do this?

Depends on what your JavaScript code is doing and where it is located. It the worst case you will get runtime errors because you are trying to access DOM elements before they exist. This would happend if your code is located in the head and you are not only defining functions but already trying to access DOM elements.

For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?

There is no "harm" per se. It would just not work if the the script is located in the head, because the DOM elements don't exist yet. That means, jQuery cannot find and bind the handler to them.
But if you place the script just before the closing body tag, then the DOM elements will exist.


To be on the safe side, whenever you want to access DOM elements, place these calls in the ready event handler or into functions which are called only after the DOM is loaded.

As the jQuery tutorial (you should read it) already states:

As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

To do this, we register a ready event for the document.

$(document).ready(function() {
    // do stuff when DOM is ready
});

To give a more complete example:

<html>
    <head>
        <!-- Assuming jQuery is loaded -->
        <script>

            function foo() {
                // OK - because it is inside a function which is called
                // at some time after the DOM was loaded
                alert($('#answer').html());
            }

            $(function() {
                // OK - because this is executed once the DOM is loaded
                $('button').click(foo);
            });

            // OK - no DOM access/manipulation
            alert('Just a random alert ' + Math.random());

            // NOT OK - the element with ID `foo` does not exist yet
            $('#answer').html('42');

        </script>
    </head>
    <body>
        <div id="question">The answer to life, the universe and everything</div>
        <div id="answer"></div>
        <button>Show the answer</button>

        <script>
           // OK - the element with ID `foo` does exist
           $('#answer').html('42');
        </script>
    </body>
</html>
like image 90
Felix Kling Avatar answered Oct 13 '22 00:10

Felix Kling


The document.ready handler is triggered when the DOM has been loaded by the browser and ready to be manipulated.

Whether you should use it or not will depend on where you are putting your custom scripts. If you put them at the end of the document, just before the closing </body> tag you don't need to use document.ready because by the time your script executes the DOM will already be loaded and you will be able to manipulate it.

If on the other hand you put your script in the <head> section of the document you should use document.ready to ensure that the DOM is fully loaded before attempting to modify it or attach event handlers to various elements. If you don't do this and you attempt to attach for example a .click event handler to a button, this event will never be triggered because at the moment your script ran, the jQuery selector that you used to find the button didn't return any elements and you didn't successfully attach the handler.

like image 40
Darin Dimitrov Avatar answered Oct 12 '22 23:10

Darin Dimitrov