The main way to insert JavaScript into an HTML page is to use the <script> element. This element was created by Netscape and first implemented in Netscape Navigator 2. Later, this element was added to the formal HTML specification. HTML 4.01 defines the following 6 properties for <script>.
- Async: Optional. Indicates that the script should be downloaded immediately, but should not interfere with other actions on the page, such as downloading additional resources or waiting for other scripts to load. Valid only for external script files.
- charset: Optional. Represents the character set of the code specified by the SRC attribute. Because most browsers ignore its value, this property is rarely used.
- defer: Optional. Indicates that the script can be deferred until the document is fully parsed and displayed before execution. Valid only for external script files. This property is also supported for embedded scripts in
IE7
and earlier versions.
- language: deprecated. Originally used to represent scripting languages (such as JavaScript, JavaScript1.2, or VBScript) used to write code. Most browsers ignore this property, so there's no need to use it anymore.
- src: Optional. Represents the external file that contains the code to execute.
- type: Optional. Can be seen as an alternative attribute of language, a content type (also known as a MIME type) that represents the scripting language in which the code is written. Although both Text/javascript and Text/ecmascript have not been recommended, people have been using text/javascript for a long time. In fact, the MIME type used by the server when transmitting JavaScript files is usually application/x–javascript, but setting this value in type may cause the script to be ignored. In addition, the following values can be used in non-IE browsers:
application/javascript
and application/ecmascript
. Given the conventional and maximum browser compatibility, the current value of the type attribute is still text/javascript. However, this property is not required, and if this property is not specified, its default value is still text/javascript. There are two ways to use the <script> element in
- : Embed JavaScript code directly in the page and include external JavaScript files.
When embedding JavaScript code with the <script> element, you only need to specify the Type property for <script>. Then, put the JavaScript code directly inside the element as follows:
<script type= "Text/javascript" >function Sayhi () {alert ("hi!");} </script>
The JavaScript code contained within the <script> element will be interpreted from top to bottom. Taking the previous example, the interpreter interprets the definition of a function and then saves the definition in its own environment. Until all code inside the <script> element is evaluated by the interpreter, the rest of the page will not be loaded or displayed by the browser. When using <script>
embedded JavaScript code, remember not to have the "" string anywhere in your code </script>
.
For example, the browser will generate an error when loading the code shown below:
<script type= "Text/javascript" >function Sayscript () {alert ("</script>"); } </script>
Because by parsing the rules of embedded code, when the browser encounters the string " </script>
", it is considered to be the end </script>
tag. This can be solved by escaping the character " /
", for example:
<script type= "Text/javascript" >function Sayscript () {alert ("<\/script>");} </script>
Run for a minute
This allows the code browser to be acceptable, so it will not cause errors.
The SRC attribute is required if you want to include an external JavaScript file through the <script> element. The value of this property is a link to an external JavaScript file, for example:
<script type= "Text/javascript" src= "Example.js" ></script>
In this example, the external file example.js will be loaded into the current page. The external file must contain only those JavaScript code that is normally placed between the start <script> and end </script>. As with the parsing of embedded JavaScript code, the processing of the page is temporarily stopped when parsing an external JavaScript file, including downloading the file. If you are in an XHTML document, you can omit the </script> tag that ends in the previous sample code, for example:
<script type= "Text/javascript" src= "Example.js"/>
However, you cannot use this syntax in an HTML document. The reason for this is that this syntax does not conform to the HTML specification and is not properly parsed by some browsers, especially IE.
as a rule, external JavaScript files have a. js extension. However, this extension is not required because the browser does not check the extension of the file that contains the JavaScript. This makes it possible to dynamically generate JavaScript code using JSP, PHP, or other server-side languages. However, the server usually needs to look at the extension to determine which MIME type to apply to the response. If you do not use the. js extension, make sure that the server returns the correct MIME type.
It is important to note that the <script> element with the SRC attribute should not contain additional JavaScript code between its <script> and </script> tags. If embedded code is included, only the external script file is downloaded and executed, and the embedded code is ignored.
In addition, the SRC attribute of the <script> element can also contain JavaScript files from the external domain. This makes the <script> element more powerful and controversial. At this point, <script> is very similar to the element, that is, its SRC attribute can be a full URL to a domain outside the domain of the current HTML page, for example:
<script type= "Text/javascript" src= "Http://www.somewhere.com/afile.js" ></script>
In this way, code that is located in the external domain is loaded and parsed as if the code were in the page where they were loaded. This makes it possible to provide JavaScript files through different domains when necessary. However, be careful when accessing JavaScript files on servers that you cannot control. If a malicious programmer is unfortunate, they can replace the code in the file at any time. Therefore, if you want to include code from different domains, either you are the owner of that domain, or the owner of that domain is trustworthy.
Regardless of the code, as long as there are no defer and async attributes, the browser will parse the <script> elements sequentially in the order they appear in the page. In other words, after the first <script> element contains the code parsing complete, the second <script> contains the code to be parsed, and then the third, fourth ...
2.1.1 The location of the label
As a traditional practice, all <script> elements should be placed in the
<! DOCTYPE html>
The purpose of this approach is to place references to all external files (including CSS files and JavaScript files) in the same places. However, including all JavaScript files in the
<! DOCTYPE html>
This way, the contents of the page are fully rendered in the browser before parsing the included JavaScript code. Users will also feel the speed of opening the page because of the shortened time of the browser window showing blank pages.
2.1.2 Delay ScriptHTML 4.01 defines the defer property for the <script> tag. The purpose of this property is to indicate that the script executes without affecting the construction of the page. In other words, the script is deferred until the entire page has been parsed and then run. Therefore, setting the Defer property in the <script> element is equivalent to telling the browser to download it immediately, but defer execution.
<! DOCTYPE html>
In this example, although we put the <script> element in the
As mentioned earlier, the Defer property applies only to external script files. This is already specified in HTML5, so the implementation that supports HTML5 ignores the defer property that is set for the embedded script. IE4~IE7 also supports defer properties for embedded scripts, but IE8 and later versions fully support HTML5-defined behavior.
IE4, Firefox 3.5, Safari 5, and Chrome are the first browsers to support defer properties. Other browsers ignore this property and process the script as usual. For this reason, placing the deferred script at the bottom of the page is still the best option.
In the
XHTML document, set the Defer property to Defer= "defer".
2.1.3 Asynchronous scriptHTML5 defines the async attribute for the <script> element. This property is similar to the defer property and is used to change the behavior of the processing script. Similarly to defer, Async applies only to external script files and tells the browser to download the file immediately. Unlike defer, however, scripts marked as Async are not guaranteed to be executed in the order in which they are specified. For example:
<! DOCTYPE html>
In the above code, the second script file may be executed before the first script file. Therefore, it is important to ensure that they are not dependent on each other. The purpose of specifying the async attribute is to not allow the page to wait for two scripts to download and execute, thus loading the page's other content asynchronously. For this reason, it is recommended that asynchronous scripts do not modify the DOM during loading.
Asynchronous scripts must be executed before the Load event of the page, but may be executed before or after the domcontentloaded event is triggered. Browsers that support asynchronous scripting have Firefox 3.6, Safari 5, and Chrome.
In the
XHTML document, set the Async property to Async= "Async".
The usage of 2.1.4 in XHTML ①Extensible Hypertext Markup Language, XHTML (extensible Hypertext Markup Language), is a standard that is redefined as an application of HTML as XML. The rules for writing XHTML code are much stricter than writing HTML and directly affect the ability to use <script/> tags when embedding JavaScript code. In the following code block, for example, although they are valid in HTML, they are not valid in XHTML.
<script type= "Text/javascript" >function compare (A, B) {if (a < b) {alert ("A is less than B");} else if (a > B) {Alert ("A is greater than B");} else {alert ("A is equal to B");}} </script>
In HTML, there are special rules to determine which content in the <script> element can be parsed, but these special rules do not apply in XHTML. The less than sign (<) in the comparison statement a < b here will be interpreted as starting a new label in XHTML. However, as a label, the less-than-sign cannot be followed by a space, resulting in a syntax error.
①HTML5 is rapidly being adopted by front-end developers, suggesting that readers follow HTML5 standards in their learning and development, and this section can be skipped.
There are two ways to avoid a similar syntax error in XHTML. One is (<)
to replace all the less-than-sign () in the code with the corresponding HTML entity <
, and the replacement code looks like this:
<script type= "Text/javascript" >function compare (A, B) {if (A & lt; b) {alert ("A is less than B");} else if (a &G T b) {alert ("A is greater than B"),} else {alert ("A is equal to B");}} </script>
While this allows the code to function correctly in XHTML, it makes the code difficult to understand. To do this, we can consider another approach.
A second way to ensure that the same code works correctly in XHTML is to include JavaScript code with a CData fragment. In XHTML (XML), CData fragments are a special area in a document that can contain text content in any format that you do not need to parse. As a result, any character can be used in a CData fragment--less than the number is of course not a problem and does not result in a syntax error. The JAVASCRIPT code block after introducing a CData fragment is as follows:
<script type= "Text/javascript" ><! [Cdata[function Compare (A, B) {if (a < b) {alert ("A is less than B"), or else if (a > B) {alert ("A is greater than B") ;} else {alert ("A is equal to B");}]] > </script>
In an XHTML-compatible browser, this approach solves the problem. In reality, however, there are many browsers that are incompatible with XHTML and therefore do not support CData fragments. What do we do? Then use JavaScript Annotations to comment out the CData tags:
<script type= "Text/javascript" >//<! [Cdata[function Compare (A, B) {if (a < b) {alert ("A is less than B"), or else if (a > B) {alert ("A is greater than B") ;} else {alert ("A is equal to B");}} ]]></script>
This format is available in all modern browsers. Although it has a somewhat hack flavor, it can be verified by XHTML, and the browser will degrade smoothly before XHTML.
XHTML mode is triggered when the MIME type of the page is specified as "Application/xhtml+xml". Not all browsers support the provision of XHTML documents in this manner.
2.1.5 syntax not recommended for useIn the early introduction of the <script> element, this element is in conflict with the parsing rules of traditional HTML. Because of the special parsing rules that are applied to this element, it can cause problems in browsers that do not support JavaScript (most typically Mosaic). Specifically, browsers that do not support JavaScript will output the contents of the <script> element directly to the page, which will break the layout and appearance of the page.
Netscape and Mosaic negotiated and proposed a solution that allows browsers that do not support <script> elements to hide embedded JavaScript code. The solution is to include the JavaScript code in an HTML comment, like this:
<script><!--function Sayhi () {alert ("hi!");} --></script>
When you add HTML annotations to a script, browsers such as Mosaic ignore the contents of the <script> tag, and those browsers that support JavaScript must further confirm that they contain JavaScript code that needs to be parsed when they encounter this situation.
Although the format of this annotated JavaScript code is recognized by all browsers, it can be interpreted correctly, but since all browsers already support JavaScript, there is no need to use this format anymore. In XHTML mode, scripts are ignored because they are contained in XML annotations.
2.1 <script> Elements "JavaScript Advanced Programming Third Edition"