为什么脚本在body标签的末尾? [英] Why scripts at the end of body tag

查看:281
本文介绍了为什么脚本在body标签的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题被问了很多次,但我还没有找到答案。那么为什么它推荐将脚本包含在body标签的末尾以便更好地呈现呢?

I know this question was asked many times, but I haven't found answer. So why its recommended to include scripts at the end of body tag for better rendering?

从Udacity课程 https://www.udacity.com/course/ ud884 - 在DOM和CSSOM准备就绪后渲染开始。 JS是HTML分析阻止,任何脚本在CSSOM准备就绪后启动。

From Udacity course https://www.udacity.com/course/ud884 - rendering starts after DOM and CSSOM are ready. JS is HTML parse blocking and any script starts after CSSOM is ready.

因此,如果我们得到:

So if we got:

<html>
    <head>
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>CRP</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <!-- content -->
        <script src="script.js"></script>
    </body>
</html>

CRP是:

CRP would be:

CSSOM ready > JS execute > DOM ready > Rendering

如果脚本在头:

And if script is at head:

<html>
    <head>
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>CRP</title>
        <link rel="stylesheet" href="styles.css">
        <script src="script.js"></script>
    </head>
    <body>
        <!-- content -->
    </body>
</html>

CRP将会是相同的:

CRP would be the same:

CSSOM ready > JS execute > DOM ready > Rendering

这个问题只关于sync脚本(没有async / defer属性)。

This question is only about "sync" scripts (without async/defer attribute).

推荐答案

历史上,脚本阻止了更快速下载更多资源。通过将它们放置在底部,您的风格,内容和媒体可以更快地下载,从而提高性能。

Scripts, historically, blocked additional resources from being downloaded more quickly. By placing them at the bottom, your style, content, and media could download more quickly giving the perception of improved performance.

更多阅读: 异步 defer 属性。

Further reading: The async and defer attributes.

这篇关于为什么脚本在body标签的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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