页面中脚本标记的位置如何影响其中定义的JavaScript函数? [英] How does the location of a script tag in a page affect a JavaScript function that is defined in it?

查看:87
本文介绍了页面中脚本标记的位置如何影响其中定义的JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到应该在< head> 标记中定义JavaScript函数,但是< script> (无论在< head> < body> 或任何其他标记)影响JavaScript函数。



具体而言,它是如何影响函数的范围以及可以从哪里调用的?

解决方案

告诉人们只在头部声音中添加< SCRIPT> 是一件合理的事情。正如其他人所说的那样,为什么不推荐这种做法,甚至是不切实际的原因有很多 - 主要是速度和HTML页面动态生成的方式。

这就是< HTML 4规范说


SCRIPT元素在文档中放置一个脚本
。此元素可能
在HTML文档的HEAD
或BODY中出现次数。一些示例HTML。 )

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD HTML 4.01 // EN
http://www.w3.org/TR/html4/strict.dtd\">
< HTML>
< HEAD>
< TITLE>含SCRIPT< / title>的文件
< META http-equiv =Content-Script-Typecontent =text / tcl>
< SCRIPT type =text / vbscriptsrc =http://someplace.com/progs/vbcalc>
< / SCRIPT>
< / HEAD>
< BODY>
< SCRIPT type =text / javascript>
...一些JavaScript ...
< / SCRIPT>
< / BODY>
< / HTML>

以及在 HTML 5
$ b < SCRIPT>中的新异步属性


注意:有些方法[sic]脚本可以执行



async属性为true:
脚本将与页面的其余部分异步执行
,因此
脚本将

async属性为false,但
defer属性为true:
脚本将在页面
完成分析时执行。



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?

解决方案

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.

This is what the 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.

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>

And something to look forward to in HTML 5 :

New async attribute in <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函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆