When exactly the $(document).ready callback is executed?

后端 未结 6 1147
别那么骄傲
别那么骄傲 2021-01-30 19:57

Suppose that we attach a .click() handler to an anchor () tag in the $(document).ready callback. This handler will cancel the default action (following the

6条回答
  •  故里飘歌
    2021-01-30 20:10

    You have a couple of different questions here

    When exactly the $(document).ready callback is executed?

    It is executed as soon as the DOM is fully loaded. NOT when everything (such as images) are finished downloading like .load() would be. It is (in general) before that, basically it is when the page its self is built.

    What I would like to know is when exactly the callback will execute

    When it is clicked.

    is it possible for the user to click on the anchor (the document has been shown in the browser) but the event hasn't been attached yet.

    Yes, it is possible. But putting it in the .ready() give you the best chance that it will not. There are only 2 ways to do it to be 'more sure' that it will not. These are actually using the 'onclick' on the link its self, and putting the javascript directly after the link (and not in the .ready()) so that is executed immediately after the link is created.

    Also, there is no difference between how the 2 code samples you provided will work. However, in the second one you do not need to put the code in the .ready(), because it exists after the link, it will always be executed after the link has been created. If you removed it from the .ready() it would be the first of the 2 ways I described above.

    Additionally, instead of putting 'return false;' in your callback, it is better to use .preventDefault() and .stopPropagation() this will let you specify if you want to prevent the default action or stop the event from bubbling, or both.

提交回复
热议问题