简体   繁体   English

HTML JavaScript 脚本标签

[英]HTML JavaScript Script Tag

Why are javascript <script> tags placed in the <body> rather than the other script tags which are usually placed in the <head> ?为什么 javascript <script>标签放在<body>中,而不是通常放在<head>中的其他script标签?

  1. JavaScript is blocking; JavaScript 正在阻塞; it is often desirable prioritise rendering HTML over loading of JS.通常需要优先渲染 HTML 而不是加载 JS。
  2. JavaScript often needs to access elements in the DOM during its initial execution (eg to add event listeners). JavaScript 在其初始执行期间经常需要访问 DOM 中的元素(例如添加事件监听器)。 Those elements need to exist before the JS can access them.这些元素需要在 JS 可以访问它们之前存在。 Placing the <script> element after the elements it needs to access is one way to achieve this.<script>元素放在它需要访问的元素之后是实现此目的的一种方法。

The introduction of the defer attribute allows both these benefits to be gained while leaving the <script> element in the <head> which also allows the HTTP request for the JS to run in parallel. defer属性的引入允许获得这两个好处,同时将<script>元素留在<head>中,这也允许 HTTP 请求 JS 并行运行。 Not everybody has caught up with this development.并不是每个人都赶上了这一发展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM