jQuery document.ready

前端 未结 5 1975
北恋
北恋 2020-11-28 16:38

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

相关标签:
5条回答
  • 2020-11-28 16:54

    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.

    0 讨论(0)
  • 2020-11-28 17:01

    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>
    
    0 讨论(0)
  • 2020-11-28 17:05

    You put code inside of $(document).ready when you need that code to wait for the DOM to load before executing. If the code doesn't require the DOM to load first to exist, then you can put it outside of the $(document).ready.

    Incidentally, $(function() { }) is short-hand for $(document).ready();

    $(function() {
       //stuff here will wait for the DOM to load
       $('#something').text('foo'); //should be okay
    });
    
    //stuff here will execute immediately.
    /* this will likely break */
    $('#something').text('weee!');
    
    0 讨论(0)
  • 2020-11-28 17:14

    If you have your scripts at the end of the document, you dont need document.ready.

    example: There is a button and on click of it, you need to show an alert. You can put the bind the click event to button in document.ready. You can write your jquery script at the end of the document or once the element is loaded in the markup.

    Writing everything in document.ready event will make your page slug.

    0 讨论(0)
  • 2020-11-28 17:18

    There is no harm not adding event handlers in ready() if you are calling your js functions in the href attribute. If you're adding them with jQuery then you must ensure the objects these handlers refer to are loaded, and this code must come after the document is deemed ready(). This doesn't mean they have to be in the ready() call however, you can call them in functions that are called inside ready() themselves.

    0 讨论(0)
提交回复
热议问题