为什么将内联脚本放在页面底部时会阻止渲染? [英] Why do inline scripts block rendering when put at the bottom of a page?

查看:73
本文介绍了为什么将内联脚本放在页面底部时会阻止渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了高性能网站:有关前端的基本知识最终工程师,作者建议所有JavaScript代码都应该外部化,并放在页面底部,而不是放在页面顶端.

此示例中进行了说明.外部脚本标签会同时阻止页面的下载渐进式渲染,因此解决方案是将其放在页面底部./p>

但是,在他的第二本书中,甚至更快的网站:性能他谈到了Web开发人员的最佳做法,其中介绍了 Inline JavaScript标签.

内联脚本还会阻止页面的下载和呈现,因此他建议也将其移至页面底部.但是,此行为仍然完全阻塞了页面的呈现,如此示例中所示

为什么将外部脚本移动到页面底部可以让页面逐步渲染,而移动内联脚本则完全阻止渲染,直到脚本执行完毕?


PS:

问题不是关于为什么要在页面底部添加JavaScript而不是将JavaScript放在页面顶部.这就是为什么底部的内联脚本阻止渲染而底部的外部脚本却阻止渲染的原因.

解决方案

在嵌入式脚本中,运行脚本所花费的时间很长,这可能会更改DOM.试图在DOM变异时呈现DOM是造成混乱的秘诀.因此,渲染仅在JS停顿时才发生,因此DOM是稳定的.

在等待外部脚本下载时,脚本的运行被暂停,因此可以安全地呈现DOM.下载的JS在渲染完成之前不会运行.

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.

解决方案

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.

这篇关于为什么将内联脚本放在页面底部时会阻止渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆