javascript - 页面中脚本标记的位置如何影响其中定义的 JavaScript 函数?

标签 javascript html function tags

我读到您应该在 <head> 中定义您的 JavaScript 函数标记,但是 <script> 的位置如何? (无论是在 <head><body> 还是任何其他标签中)都会影响 JavaScript 函数。

具体来说,它如何影响函数的范围以及您可以从哪里调用它?

最佳答案

告诉人们添加 <SCRIPT>仅在头脑中听起来是一件合理的事情,但正如其他人所说,有很多原因不推荐甚至不实用 - 主要是速度和动态生成 HTML 页面的方式。

这就是HTML 4 spec says :

The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.

和一些示例 HTML。这里的格式看起来是不是很漂亮:)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>

HTML 5 中还有一些值得期待的东西:

<SCRIPT> 中的新异步属性:

Note: There are ways [sic] a script can be executed:

The async attribute is "true": The script will be executed asynchrously with the rest of the page, so the script will be executed while the page continues the parsing.

The async attribute is "false", but the defer attribute is "true": The script will be executed when the page is finished with the parsing.

关于javascript - 页面中脚本标记的位置如何影响其中定义的 JavaScript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/496646/

相关文章:

javascript - 使用 Electron 构建 Mac 应用程序有哪些限制?

javascript - 使用 PHP(wordpress)从数据库中删除图像及其在数据库中的记录

html - 将关闭按钮放置在不同尺寸图像的右上角

c++ - 在 C++ 中优化十六进制到 Ascii 函数

javascript - 尝试在 React w/Formik 中每次输入字段完成时创建一个计数器

javascript - Soundcloud SC.stream() : waveforms and autoplay

html - 如何只降低背景的不透明度而不降低其中的文本?

html - 如何压缩div中的元素

php - 从当前函数中取消设置所有已定义的变量

javascript - Electron 在内部存储文件