页面中脚本标记的位置如何影响其中定义的 JavaScript 函数? [英] How does the location of a script tag in a page affect a JavaScript function that is defined in it?
问题描述
我读到你应该在 标签中定义你的 JavaScript 函数,但是
的位置如何(是否在
code>
或任何其他标签)影响 JavaScript 函数.
I read that you should define your JavaScript functions in the <head>
tag, but how does the location of the <script>
(whether in the <head>
, <body>
, or any other tag) affect a JavaScript function.
具体来说,它如何影响函数的作用域以及您可以从哪里调用它?
Specifically, how does it affect the scope of the function and where you can call it from?
推荐答案
告诉人们只在头部声音中添加是一件合理的事情,但正如其他人所说,不推荐甚至不实用的原因有很多 - 主要是速度和动态生成 HTML 页面的方式.
Telling people to add <SCRIPT>
only in the head sounds like a reasonable thing to do, but as others have said there are many reasons why this isn't recommended or even practical - mainly speed and the way that HTML pages are generated dynamically.
这是 HTML 4 规范所说的:
SCRIPT 元素放置一个脚本一个文件内.这个元素可能在 HEAD 中出现任意次数或 HTML 文档的 BODY.
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.看起来不是都格式化在这里吗:)
And some sample HTML. Doesn't it look pretty all formatted here :)
<!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 :
And something to look forward to in HTML 5 :
中的新异步属性:
注意:有多种方法 [原文如此] 脚本可以执行:
Note: There are ways [sic] a script can be executed:
异步属性为true":脚本将异步执行与页面的其余部分,所以脚本将在页面执行时执行继续解析.
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.
async 属性是false",但是defer 属性为true":脚本将在页面时执行解析完毕.
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 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!