Why is it good to put script tag in the end of body tag?

99封情书 提交于 2019-12-05 00:18:07

问题


There are two events related to web page initialization of browser.

  • DOMContentReady(document object) : HTML document was parsed and DOM tree was constructed
  • load(window object) : All element of HTML document were rendered(displayed)

In my understanding, browser can't start rendering page before DOM is ready(DOMContentReady is fired) and by default script tag blocks any other browser process until script file is downloaded and executed.

Then why is it good to put script tag in the end of body tag? In my opinion, browser will be blocked when it meets script tag in any position of the page, so DOMContentReady will not be fired until script tag is downloaded and executed. As a result, user can't see anything except white blank page until script is fully processed regardless of position of script tag.


回答1:


Modern browsers will download the page content and display it as it is downloaded. If your script tags are before the body, the browser may download all of your scripts before anything begins to show up, which may be an undesirable amount of time to make often impatient users wait before they get to see anything.

Putting your script tags at the end of the body tag, after all of the page's contents, means your entire page will begin displaying as soon as possible to give the user something to look at - and then your scripts will download and make everything work.

In my understanding, browser can't start rendering page before DOM is ready (...) As a result, user can't see anything except white blank page until script is fully processed regardless of position of script tag.

This isn't the case. Modern browsers will display the page's content whilst it's still being downloaded, and display each bit of the page as soon as it can make enough sense of it to do so.



来源:https://stackoverflow.com/questions/17140386/why-is-it-good-to-put-script-tag-in-the-end-of-body-tag

工具导航Map