Why is jQuery.ready recommended when it’s so slow?

后端 未结 4 1871
眼角桃花
眼角桃花 2021-01-31 09:07

I have asked a similar question before but I never made my point exactly clear, or at least I think it’s such a relevant question that it’s worth to bring it up and see if anyon

4条回答
  •  粉色の甜心
    2021-01-31 09:32

    If you've written a JS file that other people are including in their pages it is safer to use document.ready within that file (assuming it needs to do some processing automatically after the DOM is ready) because you can't be sure whether the file will be included in the head or at the end of the body.

    When it comes to pages that you have complete control over then obviously you don't have that worry, so I don't see that it is any more "safe" to use document.ready rather than calling your init() from the end of the body. Using document.ready (or onload) and putting script at the end of the body are the two most common ways to do it, and they're common because they both work well.

    You mentioned document.write() as a possible exception, but you don't want to be calling that from document.ready or at the end of the body because either way the whole page has already been parsed.

提交回复
热议问题