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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!