Jquery has a ready method:

$(document).ready(function(){
   // my code
})

It will execute my code when dom is ready.

I have a question, if I put all my scripts after </body>, e.g.

<html>
    <body>
       // all kinds of html tags
    </body>
    <script src="/path/to/jquery.js"></script>
    <script src="/path/to/all-javascript-compressed-in-one-file.js"></script>
</html>

Do I still need to write $(document).ready()? Is the dom already ready after </body>?

有帮助吗?

解决方案

Usually, the scripts are added just before </body>, not after it – the HTML won't validate otherwise; no content can appear outside <head>, or <body>, as noted by Šime Vidas on his comment.

That being said, technically the DOM is not considered ready yet at that point (as the browser is still parsing the <body>), but already contains all elements from the body. Thus, it's safe to skip $(document).ready().

Doing that will execute your initialization scripts earlier, since there is some delay before the actual DOMContentLoaded event is fired. That means a faster page load, and a better user experience.

You might be interested in this related discussion about forcing the jQuery ready event.

其他提示

In a word, no. The dom is considered "ready" when the dom tree is available, if your javascript is the last thing on the page, then everything before it is "ready", as web pages are "loaded" from the top down.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top