Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS 放在 head 里和放在 body 里有什么区别?【热度: 420】 #677

Open
yanlele opened this issue Apr 6, 2024 · 0 comments
Open
Labels
web应用场景 应用场景类问题 阿里巴巴 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Apr 6, 2024

将 JavaScript 代码放在 <head> 标签内部和放在 <body> 标签内部有一些区别:

  1. 加载顺序:放在 <head> 里会在页面加载之前执行 JavaScript 代码,而放在 <body> 里会在页面加载后执行。
  2. 页面渲染:如果 JavaScript 代码影响了页面的布局或样式,放在 <head> 里可能会导致页面渲染延迟,而放在 <body> 里可以减少这种影响。
  3. 代码依赖:如果 JavaScript 代码依赖其他元素,放在 <body> 里可以确保这些元素已经加载。
  4. 全局变量和函数:放在 <head> 里的 JavaScript 代码中的全局变量和函数在整个页面生命周期内都可用。

以下是一个简单的示例代码,展示了如何在 <head><body> 中放置 JavaScript 代码:

<!DOCTYPE html>
<html>

<head>
  <script>
    console.log("这是在 head 中执行的 JavaScript 代码。");
  </script>
</head>

<body>
  <script>
    console.log("这是在 body 中执行的 JavaScript 代码。");
  </script>
</body>

</html>

在这个示例中,分别在 <head><body> 中放置了简单的 JavaScript 代码,用于在控制台输出信息,以便观察执行顺序。

@yanlele yanlele added 网络 web 网络相关 阿里巴巴 公司标签 labels Apr 6, 2024
@yanlele yanlele added this to the milestone Apr 6, 2024
@yanlele yanlele added web应用场景 应用场景类问题 and removed 网络 web 网络相关 labels Apr 6, 2024
@yanlele yanlele modified the milestones: , Apr 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web应用场景 应用场景类问题 阿里巴巴 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant