浏览器对< script>里面< body> [英] Browsers react differently to <script> inside <body>

查看:58
本文介绍了浏览器对< script>里面< body>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我无法理解的问题。看看这个JS代码:



<!DOCTYPE HTML>< html> ;< HEAD> < meta charset =utf-8>< / head>< body> < p>开始...< / p> <脚本>警报('你好,Wolrd!'); < /脚本> < p> ... The End Of Doc< / p>< / body>< / html>



所以问题是我不明白为什么开始段在<$ c $之前没有加载/可见c>< script> 标签。在几乎所有的教程中都解释说,浏览器在符合脚本之前加载所有的HTML,然后当符合脚本时,浏览器开始以脚本的编译模式工作,然后当脚本以HTML模式结束浏览器时返回。

但实际上,它的行为似乎有所不同,因为开始文本仅在 em> script alert:





可以请某人解释为什么发生这种情况?






PS:只有Firefox的行为与教程中描述的一致。

解决方案

脚本之前的元素已经创建并添加到DOM,但浏览器没有机会渲染它们(更新页面显示来显示它们)在 alert 之前使整个UI线程停止响应。浏览器需要创建元素并将它们添加到DOM;这是 不需要呈现它们。有些人会,有些人不会。我们可以很容易地证明第一段通过查找它甚至阅读它的文本而存在:
$ b


开始...< / p>< script>< p> alert(Hello,World!First paragraph's text:+ document.querySelector(p)。textContent);< / script>< p> ... The End Of Doc< / p>


Here is the problem I can't understand. Look at this JS code:

<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
</head>

<body>
  <p>The Beginning...</p>
  <script>
    alert('Hello, Wolrd!');
  </script>
  <p>...The End Of Doc</p>
</body>

</html>

So the problem is that I do not understand why The Beginning paragraph isn't loaded/visible before the <script> tag. In almost all tutorials it's explained that the browser loads all HTML before it meets script, then when the script is met the browser starts working in script's compilation mode and then when the script ends browser returns in HTML mode.

But on practic it seems that it behaves differently, as The Beginning text appears only after script alert:

Could please someone explain why is that happening?


PS: Only Firefox behaves as described in the tutorials.

解决方案

The elements from before the script have been created and added to the DOM, but the browser hasn't had a chance to render them (update the page display to show them) before the alert brings the whole UI thread to a screeching halt. The browser is required to have created the elements and added them to the DOM; it is not required to have rendered them yet. Some will, some won't. Neither is "wrong."

We can readily prove that the first paragraph exists by looking for it and even reading its text:

<p>The Beginning...</p>
<script>
  alert("Hello, World! First paragraph's text: " + document.querySelector("p").textContent);
</script>
<p>...The End Of Doc</p>

这篇关于浏览器对&lt; script&gt;里面&lt; body&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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