简体   繁体   English

将脚本放入 head 和 body 有什么区别?

[英]What's the difference between putting script in head and body?

I was getting a problem .我遇到了问题。

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script type="text/javascript">
  alert(document.getElementsByTagName("li").length); 
  </script>
  <title>purchase list</title>
</head>
<body>
  <h1>What to buy</h1>
  <ul id="purchases">
    <li> beans</li>
    <li>Cheese</li>
  </ul>
</body>

When I put scripts in head, the result shows 0当我将脚本放在头中时,结果显示为 0

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Shopping list</title>
</head>
<body>
  <h1>What to buy</h1>

  <ul id="purchases">
    <li>Cheese</li> 
    <li>Milk</li>
    <script type="text/javascript">
    alert(document.getElementsByTagName("li").length);
    </script>
  </ul>
</body>

When I tried to put scripts in body, the result shows 2. why there is such a difference?当我尝试将脚本放入正文时,结果显示 2. 为什么会有这样的差异? what is the main difference?主要区别是什么?

What's the difference between putting script in head and body?将脚本放入 head 和 body 有什么区别?

The time that it runs.它运行的时间。

When I put scripts in head, the result shows 0 Shopping list当我把脚本放在头里时,结果显示 0 购物清单

The elements you are trying to access don't exist when the script runs (since they appear after the script in the document).当脚本运行时,您尝试访问的元素不存在(因为它们出现在文档中的脚本之后)。

Note that you can write a script so that a function is called later (for various values of later including "when the entire document has loaded") using event handlers .请注意,您可以编写一个脚本,这样的功能是后来被称为(为以后包括“当整个文件已加载”不同的值)使用的事件处理程序

It's simple, JavaScript will go from up-down, unless you tell it to do something else.很简单,JavaScript 会自上而下,除非你告诉它做其他事情。 By the time it reaches the li elements, the JavaScript code has already been completed.当它到达 li 元素时,JavaScript 代码已经完成。

If you want to keep it in the head however, you could use the document.ready function and it will load only after the HTML it's loaded.但是,如果您想将其保留在头脑中,则可以使用 document.ready 函数,它只会在加载 HTML 之后加载。

Head will get rendered before Body. Head 将在 Body 之前渲染。 If you're trying to access your li tags in the head, the obvious answer is that they are not created until the browser renders the body section and therefore cannot be referenced.如果您尝试访问头部中的li标签,显而易见的答案是它们在浏览器呈现正文部分之前不会创建,因此无法被引用。

Because at the time of you calling it in the head, the li doesn't yet exist (As far as the DOM is concerned) – F4r-20 1 min ago因为当你在头脑中调用它时,li 还不存在(就 DOM 而言) – F4r-20 1 分钟前

This is correct.这是对的。 But, try this:但是,试试这个:

 <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript"> window.onload = function(){ alert(document.getElementsByTagName("li").length); } </script> <title>purchase list</title> </head> <body> <h1>What to buy</h1> <ul id="purchases"> <li> beans</li> <li>Cheese</li> </ul> </body>

When scripts are included in the head they load or run before the content of the page.当脚本包含在头部时,它们会在页面内容之前加载或运行。 When you include them in the body they load or run after the preceding html.当您将它们包含在正文中时,它们会在前面的 html 之后加载或运行。 It's usually good practice to put scripts as close to the end of the body as possible.将脚本尽可能靠近正文的末尾通常是一种很好的做法。

When you call:你打电话的时候:

alert(document.getElementsByTagName("li").length); 

You want to get an element that does not exist yet.您想要获取尚不存在的元素。 because the head is the first thing that runs when you load the page.因为 head 是加载页面时首先运行的东西。

it's searching for the li element, but it isn't yet there when the head loads.它正在搜索li元素,但是当头部加载时它还不存在。

You have to put it in the body because then, the list items exist.你必须把它放在正文中,因为那样的话,列表项就存在了。 then it works.那么它的工作原理。

Generally scripts and CSS files must be fit into head, as good practice.通常脚本和 CSS 文件必须放入 head 中,这是一种很好的做法。

For more details about when to put in head and body tag, refer this link - Where should I put the CSS and Javascript code in an HTML webpage?有关何时放入 head 和 body 标签的更多详细信息,请参阅此链接 -我应该将 CSS 和 Javascript 代码放在 HTML 网页中的何处? & Should I write script in the body or the head of the html? &我应该在正文中还是在 html 的头部编写脚本?

If you put script in head, javascript code gets executed even before controls in body tags are rendered.如果你把脚本放在 head 中,javascript 代码甚至在 body 标签中的控件被呈现之前就会被执行。 So if you want to keep your scripts in head tag, make sure they are executed once onload is completed.因此,如果您想将脚本保留在 head 标记中,请确保在 onload 完成后执行它们。 Below is an example:下面是一个例子:

 <script type="text/javascript">
function MyFunction() {
    alert(document.getElementsByTagName("li").length);
}
window.onload = MyFunction;
</script>

Following code executes the script in the head tag.以下代码执行 head 标签中的脚本。 Once without JQuery and then with JQuery that instructs the alert to display when the document is loaded $(document).reaady()一次没有使用 JQuery,然后使用 JQuery 指示在加载文档时显示警报$(document).reaady()

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script src="jquery-3.5.1.min.js"></script>
    <script type="text/javascript">
      // First alert will show # of opttions as 0, because the document is not ready yet
      alert(document.getElementsByTagName("li").length);
      // First alert will show the correct # of opttions as 2
      $(document).ready(function () {
        alert(document.getElementsByTagName("li").length);
      });
    </script>

    <title>purchase list</title>
  </head>
  <body>
    <h1>What to buy</h1>
    <ul id="purchases">
      <li>beans</li>
      <li>Cheese</li>
    </ul>
  </body>

HTML document executes in Top-Down Approach. HTML 文档以自上而下的方式执行。

  • In your case when you execute your HTML Document, it will execute head first.就您而言,当您执行 HTML 文档时,它将首先执行 head。 and as you can see, you wrote a script tag inside the head.正如你所看到的,你在头部内部写了一个脚本标签。

  • so, here a script tag will execute first.因此,这里将首先执行脚本标记。 inside a script tag what you are going to do, you are finding the length of li tag which is available inside the body tag.在脚本标签中,您将要执行的操作是找到 body 标签内可用的 li 标签的长度。

  • but at this moment, the browser doesn't execute the body tag yet.但此时,浏览器还没有执行 body 标签。

  • so, your script will get 0 as the result.因此,您的脚本将获得 0 作为结果。

    alert(document.getElementsByTagName("li").length);警报(document.getElementsByTagName(“li”)。长度);

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

相关问题 将javascript放在头部或身体之间有区别吗? - is there a difference between putting a javascript in the head or in the body? HTML <head>和<body>标签之间有什么区别? - What's the difference between HTML <head> and <body> tags? $(document).ready()和包含身体末尾的脚本有什么区别? - What's the difference between $(document).ready() and including a script at the end of the body? 什么是优点和缺点:将javascript放在头部并放在身体关闭之前 - What's Pros and Cons: putting javascript in head and putting just before the body close onLoad,onDomready,No wrap-in之间有什么区别 <head> ,没有包装 <body> ? - What is the difference between onLoad, onDomready, No wrap - in <head>, and No wrap - in <body>? 将脚本放在正文中还是正文中的区别 - difference between putting scripts in body or outside body 此JavaScript代码有什么问题? (主体脚本调用head函数) - What's wrong with this javascript code? (body script calling head function) 有什么区别 <head> 和 <asp:Content ID=“HeaderContent” …> ? - What's the difference between <head> and <asp:Content ID=“HeaderContent” …>? 包含时有什么区别<script> tag in HTML's header or body - What is the difference when including <script> tag in HTML's header or body 将 javascript 放入文件和脚本标签有什么区别? - What is the difference in putting a javascript in a file and in a script tag?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM