【问题标题】:Is a script in the footer "render-blocking"?页脚中的脚本是否“阻止渲染”?
【发布时间】:2017-07-06 15:48:25
【问题描述】:

在与同事讨论后,我们需要一个问题的答案:页脚中的脚本是否“阻止渲染”?我的意思是,在脚本完全加载之前是否向用户显示了任何内容?

谢谢

【问题讨论】:

  • 是的,它正在阻塞。但是(body)之前的部分已经渲染好了
  • 我会说任何不是 inline 或 asyc/deferred 的 JS 都是渲染阻塞的。
  • Benefits of loading JS at the bottom as opposed to the top of the document 的可能重复项 - 此外 jQuery 可能最好放在顶部,因为其他脚本可以立即使用它
  • @Fran 我不确定它们是否相同。一个是讨论好处,另一个是要求定义。
  • @evolutionxbox - 我以为它回答了这个问题If I put it in the footer, will rendering start before the script finishes downloading?

标签: javascript html rendering


【解决方案1】:

来晚了,但我找到了答案:不,脚本不是渲染阻塞,脚本是解析阻塞。只有 CSS 文件是渲染阻塞的。

如果脚本在正文中,它将是解析阻塞的,但在脚本之前解析的内容已经可以呈现(如果它在头部,则不会呈现任何内容,因为尚未解析任何内容)。所以,是的,可以在脚本完全下载之前显示/渲染内容。

请看这两个例子:

Screenshot Test1: Content rendered before the large JS file finishes downloading

<!DOCTYPE html>
<html lang="en"> 
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="css/style.css">
</head>
<body>
	<section>
		<h2>testing</h2>
		<h4>Lorem Ipsum has been the industry's standard dummy text printer took a galley of type and scrambled</h4>
		<img src="img/icon_128.png" width="128px" alt="">
		<h3>We are testing</h3>
		<p>Lorem Ipsum is simply dummy text of the printing and typesf own printer.</p>
	</section>
	<script src="js/main.js"></script>
</body>
</html>

Screenshot Test2: Content before the large JS file is rendered. The rest has to wait until the JS finishes downloading

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="css/style.css">
</head>
<body>
	<section>
		<h2>testing</h2>
		<h4>Lorem Ipsum has been the industry's standard dummy text printer took a galley of type and scrambled</h4>
		<img src="img/icon_128.png" width="128px" alt="">
		<script src="js/main.js"></script>
		<h3>We are testing</h3>
		<p>Lorem Ipsum is simply dummy text of the printing and typesf own printer.</p>
	</section>
</body>
</html>

【讨论】:

    【解决方案2】:

    当您将 javascript 放置在页面的页脚中时;即在没有 hte defer/async 属性的关闭&lt;/body&gt; 之前,它是渲染阻塞。

    当浏览器构造 DOM 并且即使在页脚中也读取了一个脚本标签并且没有defer/async属性,那么,如果脚本完整,浏览器只能继续构建DOM已下载。

    注意 DOM 结构在浏览器中还不可见,直到浏览器绘制结果。

    在我们真正看到结果之前,浏览器会执行 4 个主要步骤。

    1. DOM 和 CSSOM 结构。
    2. 渲染树
    3. 布局 - 计算每个对象的确切位置和大小。
    4. 油漆 - 是最后一步;将生成的像素渲染到屏幕上。

    Removing Render-Blocking JavascriptRender-tree Construction, Layout, and Paint 的链接

    【讨论】:

      【解决方案3】:

      一般来说,每个脚本都是一个拦截器,但是最好把js放在footer中。

      HTML 页面由浏览器逐行执行,就像您的代码一样。如果您的脚本将在页脚中 - 这意味着该脚本之前的所有内容 - 都已呈现。

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-20
        • 1970-01-01
        • 1970-01-01
        • 2010-12-28
        • 1970-01-01
        相关资源
        最近更新 更多