HTML <script> src 属性

定义和用法

src 属性规定外部脚本文件的 URL。

如果您想在网站的多个页面上运行相同的 JavaScript,则应该创建一个外部 JavaScript 文件,而不是一遍又一遍地编写相同的脚本。使用 .js 扩展名保存脚本文件,然后使用 <script> 标记中的 src 属性引用它。

注意:外部脚本文件中不能包含 <script> 标签。

Tip:Already set src The script element cannot contain content. You cannot define both inline and external scripts using the same script element.

Tip:The script element that references an external script should have no content. If an external script is referenced using a self-closing tag, the browser will ignore this element and not load the referenced file.

Example

Point to an external JavaScript file:

<script src="myscripts.js"></script>

Try it yourself

Syntax

<script src="URL">

Attribute value

Value Description
URL

URL of the external script file.

Possible values:

  • Absolute URL - points to another website (e.g., src="http://www.example.com/example.js")
  • Relative URL - points to a file within the website (e.g., src="/scripts/example.js")

Browser support

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Support Support Support Support Support