jQuery document.ready

前端 未结 5 2025
北恋
北恋 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 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:

    
        
            
            
        
        
            
    The answer to life, the universe and everything

提交回复
热议问题