为什么将脚本标记放在body标记的末尾是好的? [英] Why is it good to put script tag in the end of body tag?

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

问题描述

有两个与浏览器网页初始化相关的事件。

There are two events related to web page initialization of browser.


  • DOMContentReady(文档对象):解析了HTML文档和DOM树已构建

  • load(窗口对象):呈现(显示)HTML文档的所有元素

根据我的理解,浏览器无法在DOM准备就绪之前开始渲染页面(DOMContentReady被触发),默认情况下,脚本标记会阻止任何其他浏览器进程,直到脚本文件被下载并执行。

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.

那么为什么将script标签放在body标签的末尾呢?在我看来,当浏览器在页面的任何位置遇到脚本标记时将被阻止,因此在下载并执行脚本标记之前不会触发DOMContentReady。因此,除非脚本完全处理,否则用户无法看到除白色空白页之外的任何内容,无论脚本标记的位置如何。

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.

推荐答案

现代浏览器将下载页面内容并在下载时显示。如果您的脚本标记位于正文之前,浏览器可能会在任何开始显示之前下载所有脚本,这可能是一段不合时宜的时间,使得经常不耐烦用户在看到任何内容之前等待。

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.

在所有页面内容之后,将脚本标记放在body标记的末尾,意味着您的整个页面将尽快开始显示,以便为用户提供一些内容 - 然后然后您的脚本将下载并使一切正常。

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.


根据我的理解,浏览器无法在DOM准备好之前开始渲染页面(...)因此,在脚本完全处理之前,用户无法看到除白色空白页之外的任何内容脚本标记的位置。

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.

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

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