GEO

HTML中JavaScript嵌入指南:<script>标签放置与最佳实践

2026/1/23
HTML中JavaScript嵌入指南:<script>标签放置与最佳实践
AI Summary (BLUF)

This article explains the fundamentals of embedding JavaScript in HTML documents, covering script placement within and tags, inline vs. external scripts, and basic event handling. (本文介绍了在HTML文档中嵌入JavaScript的基础知识,涵盖脚本在和标签中的放置、内联脚本与外部脚本的区别以及基本事件处理。)

Introduction

JavaScript has become an indispensable part of modern web development, enabling dynamic and interactive user experiences. For JavaScript code to be executed by a web browser within an HTML document, it must be correctly integrated using the <script> element. This post explores the fundamentals of including JavaScript in HTML, covering the syntax of the <script> tag, its placement within the document structure, and best practices for organization.

JavaScript 已成为现代 Web 开发不可或缺的一部分,它使得动态和交互式的用户体验成为可能。为了让 Web 浏览器在 HTML 文档中执行 JavaScript 代码,必须使用 <script> 元素将其正确集成。本文将探讨在 HTML 中包含 JavaScript 的基础知识,涵盖 <script> 标签的语法、其在文档结构中的放置位置以及组织代码的最佳实践。

The <script> Tag: Syntax and Purpose

The primary method for embedding JavaScript within an HTML page is the <script> tag. This tag acts as a container, signaling to the browser where the client-side script begins and ends. The JavaScript statements are written between the opening <script> and closing </script> tags.

在 HTML 页面中嵌入 JavaScript 的主要方法是使用 <script> 标签。该标签作为一个容器,向浏览器指示客户端脚本的开始和结束位置。JavaScript 语句写在开始标签 <script> 和结束标签 </script> 之间。

Basic Syntax:

<script>
    // Your JavaScript code goes here
    alert("My First JavaScript");
</script>

基本语法:

<script>
    // 你的 JavaScript 代码写在这里
    alert("我的第一个 JavaScript");
</script>

Note on the type Attribute: In older HTML specifications, it was common to explicitly declare the script type using type="text/javascript". In modern HTML5, JavaScript is the default scripting language. Therefore, the type attribute is unnecessary for standard JavaScript and can be omitted.

关于 type 属性的说明: 在旧的 HTML 规范中,通常使用 type="text/javascript" 来显式声明脚本类型。在现代 HTML5 中,JavaScript 是默认的脚本语言。因此,对于标准 JavaScript,type 属性不是必需的,可以省略。

Placement of <script> Tags in HTML

JavaScript code can be placed in either the <head> or <body> section of an HTML document, or in both. The placement can affect script execution timing, page load performance, and code maintainability.

JavaScript 代码可以放在 HTML 文档的 <head><body> 部分,或者两者中都放。放置位置会影响脚本执行时机、页面加载性能和代码可维护性。

JavaScript in the <body> Section

Placing a <script> tag directly within the <body> is straightforward. The browser will execute the script as it parses that part of the document. This is often used for scripts that generate content immediately as the page loads.

<script> 标签直接放在 <body> 内很简单。浏览器在解析文档的该部分时会执行脚本。这通常用于在页面加载时立即生成内容的脚本。

Example: Writing content on page load

<!DOCTYPE html>
<html>
<body>
    <p>Content before the script.</p>
    <script>
        document.write("<h1>This is a heading</h1>");
        document.write("<p>This is a paragraph.</p>");
    </script>
    <p>Content after the script.</p>
</body>
</html>

示例:在页面加载时写入内容

<!DOCTYPE html>
<html>
<body>
    <p>脚本之前的内容。</p>
    <script>
        document.write("<h1>这是一个标题</h1>");
        document.write("<p>这是一个段落。</p>");
    </script>
    <p>脚本之后的内容。</p>
</body>
</html>

JavaScript Functions and Event-Driven Execution

The example above executes code immediately during page load. More commonly, JavaScript code is packaged into functions that are executed in response to events, such as a user clicking a button. This allows for interactive behavior.

上面的示例在页面加载期间立即执行代码。更常见的是,JavaScript 代码被封装到函数中,这些函数响应事件(例如用户点击按钮)而执行。这使得交互行为成为可能。

JavaScript in the <head> Section

Scripts, especially function definitions, are frequently placed in the <head> section. This ensures they are loaded and parsed early, making them available for use anywhere in the document's <body>. A common pattern is to define functions in the <head> and call them from HTML elements via event attributes (like onclick).

脚本,尤其是函数定义,经常被放在 <head> 部分。这确保了它们被尽早加载和解析,使得在文档 <body> 的任何地方都可以使用它们。一个常见的模式是在 <head> 中定义函数,并通过事件属性(如 onclick)从 HTML 元素中调用它们。

Example: Function defined in <head>, called on button click

<!DOCTYPE html>
<html>
<head>
    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = "My First JavaScript Function";
        }
    </script>
</head>
<body>
    <h1>My Web Page</h1>
    <p id="demo">A paragraph.</p>
    <button type="button" onclick="myFunction()">Click Me</button>
</body>
</html>

示例:在 <head> 中定义函数,通过按钮点击调用

<!DOCTYPE html>
<html>
<head>
    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = "我的第一个 JavaScript 函数";
        }
    </script>
</head>
<body>
    <h1>我的网页</h1>
    <p id="demo">一个段落。</p>
    <button type="button" onclick="myFunction()">点我</button>
</body>
</html>

Scripts at the End of <body> (A Common Practice)

An alternative and highly recommended practice for performance is to place <script> tags just before the closing </body> tag. This allows the browser to render the visible HTML content (CSS, images, text) to the user first, without being blocked by script downloading and execution. Scripts that manipulate DOM elements (like the example above) can still be placed here, as the DOM will be ready when they execute.

另一种备受推荐的性能优化实践是将 <script> 标签放在闭合的 </body> 标签之前。这使得浏览器可以首先向用户渲染可见的 HTML 内容(CSS、图像、文本),而不会被脚本下载和执行所阻塞。操作 DOM 元素的脚本(如上面的示例)仍然可以放在这里,因为当它们执行时,DOM 已经准备就绪。

Example: Function defined at the end of <body>

<!DOCTYPE html>
<html>
<body>
    <h1>My Web Page</h1>
    <p id="demo">A paragraph.</p>
    <button type="button" onclick="myFunction()">Click Me</button>

    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = "My First JavaScript Function";
        }
    </script>
</body>
</html>

示例:在 <body> 末尾定义函数

<!DOCTYPE html>
<html>
<body>
    <h1>我的网页</h1>
    <p id="demo">一个段落。</p>
    <button type="button" onclick="myFunction()">点我</button>

    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = "我的第一个 JavaScript 函数";
        }
    </script>
</body>
</html>

External JavaScript Files

For better code organization, reusability, and caching benefits, JavaScript is often placed in external files with a .js extension. This is achieved using the src attribute of the <script> tag.

为了更好的代码组织、可重用性和缓存优势,JavaScript 通常被放在扩展名为 .js 的外部文件中。这是通过使用 <script> 标签的 src 属性来实现的。

Key Points:

  • Separation of Concerns: Keeps HTML structure and JavaScript logic distinct.
  • Maintenance: A single .js file can be used across multiple HTML pages. Updating the script updates it everywhere.
  • Caching: Browsers can cache external JavaScript files, improving load times for subsequent page visits.

要点:

  • 关注点分离: 使 HTML 结构和 JavaScript 逻辑保持独立。
  • 可维护性: 一个 .js 文件可以在多个 HTML 页面中使用。更新脚本会在所有地方生效。
  • 缓存: 浏览器可以缓存外部 JavaScript 文件,提高后续页面访问的加载速度。

Syntax for Including an External Script:

<script src="path/to/myScript.js"></script>

引入外部脚本的语法:

<script src="路径/到/myScript.js"></script>

Example:
HTML File (index.html):

<!DOCTYPE html>
<html>
<body>
    <h1>My Web Page</h1>
    <p id="demo">A paragraph.</p>
    <button type="button" onclick="myFunction()">Click Me</button>
    <!-- Link to the external JS file -->
    <script src="myScript.js"></script>
</body>
</html>

示例:
HTML 文件 (index.html):

<!DOCTYPE html>
<html>
<body>
    <h1>我的网页</h1>
    <p id="demo">一个段落。</p>
    <button type="button" onclick="myFunction()">点我</button>
    <!-- 链接到外部 JS 文件 -->
    <script src="myScript.js"></script>
</body>
</html>

External JavaScript File (myScript.js):

function myFunction() {
    document.getElementById("demo").innerHTML = "My First JavaScript Function";
}

外部 JavaScript 文件 (myScript.js):

function myFunction() {
    document.getElementById("demo").innerHTML = "我的第一个 JavaScript 函数";
}

Important Rule: External JavaScript files must contain only JavaScript code and should not include the <script> or </script> tags themselves. The browser would treat those tags as invalid HTML/XML within a .js file.

重要规则: 外部 JavaScript 文件必须只包含 JavaScript 代码,并且不应包含 <script></script> 标签本身。浏览器会将这些标签视为 .js 文件中的无效 HTML/XML。

Summary and Best Practices

Integrating JavaScript into HTML is fundamental. The choice between inline and external scripts, as well as their placement, depends on the project's needs.

将 JavaScript 集成到 HTML 中是基础。选择内联脚本还是外部脚本,以及它们的放置位置,取决于项目的需求。

Quick Recommendations:

  1. Use External Files for Production: For any non-trivial site, use external .js files for maintainability and performance (caching).
  2. Place Scripts at the Bottom: When possible, place <script> tags just before </body> to prevent render-blocking. This is a key performance optimization.
  3. <head> for Critical Code/Pollyfills: If a script is essential for initial page rendering (e.g., a critical polyfill), it may need to be in the <head>. Consider using the async or defer attributes for such scripts to avoid blocking.
  4. Avoid document.write(): The document.write() method, used in early examples, can overwrite the entire document if called after the page loads. Modern DOM manipulation methods (like innerHTML, appendChild) are preferred.

快速建议:

  1. 生产环境使用外部文件: 对于任何重要的网站,使用外部 .js 文件以提高可维护性和性能(缓存)。
  2. 将脚本放在底部: 尽可能将 <script> 标签放在 </body> 之前,以防止渲染阻塞。这是一项关键的性能优化。
  3. 关键代码/填充库放在 <head> 如果某个脚本对初始页面渲染至关重要(例如,关键的功能填充库),则可能需要放在 <head> 中。考虑对此类脚本使用 asyncdefer 属性以避免阻塞。
  4. 避免使用 document.write() 早期示例中使用的 document.write() 方法,如果在页面加载后调用,可能会覆盖整个文档。更推荐使用现代的 DOM 操作方法(如 innerHTMLappendChild)。

By understanding these core concepts of the <script> tag, developers can effectively integrate JavaScript to create fast, interactive, and well-structured web applications.

通过理解 <script> 标签的这些核心概念,开发人员可以有效地集成 JavaScript,以创建快速、交互式且结构良好的 Web 应用程序。

← 返回文章列表
分享到:微博

版权与免责声明:本文仅用于信息分享与交流,不构成任何形式的法律、投资、医疗或其他专业建议,也不构成对任何结果的承诺或保证。

文中提及的商标、品牌、Logo、产品名称及相关图片/素材,其权利归各自合法权利人所有。本站内容可能基于公开资料整理,亦可能使用 AI 辅助生成或润色;我们尽力确保准确与合规,但不保证完整性、时效性与适用性,请读者自行甄别并以官方信息为准。

若本文内容或素材涉嫌侵权、隐私不当或存在错误,请相关权利人/当事人联系本站,我们将及时核实并采取删除、修正或下架等处理措施。 也请勿在评论或联系信息中提交身份证号、手机号、住址等个人敏感信息。