Why do inline scripts block rendering when put at the bottom of a page?

筅森魡賤 提交于 2021-02-06 12:48:12

问题


I read High Performance Web Sites: Essential Knowledge for Front-End Engineers and in it the author suggests that all JavaScript code should be externalized and put at the bottom of the page instead of putting it in the head.

This is illustrated in this example. The external script tag blocks both downloading and progressive rendering of a page, so the solution was to put it at the bottom of the page.

However, in his second book Even Faster Web Sites: Performance Best Practices for Web Developers he talks about Inline JavaScript tags.

Inline scripts also blocks downloading and rendering of a page, so he suggests moving them also to the bottom of the page. However, this acts still blocks the rendering of the page entirely as illustrated in this example

Why do moving external scripts to the bottom of the page lets the page render progressively while moving inline scripts blocks rendering completely till the script is executed?


PS:

The question isn't about why add JavaScript to the bottom of the page instead of putting them in the head. It's about why bottom inline scripts block rendering while bottom external scripts don't.


回答1:


In the inline script, the time is taken up running the script, which might change the DOM. Trying to render the DOM while it's mutating is a recipe for a mess. So rendering only happens at points when the JS is stalled, and therefore the DOM is stable.

While waiting for an external script to download, the running of scripts is stalled, so the DOM can be rendered safely. The downloaded JS won't be run until the rendering is complete.



来源:https://stackoverflow.com/questions/18292974/why-do-inline-scripts-block-rendering-when-put-at-the-bottom-of-a-page

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