jQuery document.ready

前端 未结 5 2048
北恋
北恋 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 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 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.

提交回复
热议问题