Using JavaScript in HTML

Source: Internet
Author: User

Chapter Content

    • Using <script> elements
    • Embedding scripts with external scripts
    • The impact of document mode on JavaScript
    • Consider scenarios where JavaScript is disabled

2.1 <script> Elements

The main way to insert JavaScript into an HTML page is to use the <script> element. Html4.01 defines 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, indicating the character set of the code specified by the SRC attribute. Because most browsers ignore this value, they are seldom used.

Defer: Optional. Indicates that the script can be deferred until the document is fully parsed and displayed. Valid only for external script files.

Language: Deprecated. This property is ignored by most browsers.

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 that represents the scripting language in which the code is written. 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 the property is not specified, the default value is still text/javascript.

There are two ways to use the <script> element, to embed code directly in the page and to include external JavaScript files.

When embedding JavaScript code with the <script> element, the JavaScript code contained inside the <script> element will be interpreted from top to bottom. Remember not to have the "</script>" string anywhere in your code. For example, when the browser loads the code shown below, it generates an error:

<script type= "Text/javascript" >

function Sayscript () {

alert ("</script>");

}

</script>

Because by parsing embedded code rules, when the browser encounters the string "</script>", it is considered to be the end of the </script> tag. This problem can be solved by separating the string into two parts.

<script type= "Text/javascript" >

function Sayscript () {

alert ("<\/script>");

}

</script>

If you include an external JavaScript file through the <script> element, the SRC attribute is required. 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. 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, this syntax can no longer be used in HTML documents. Because it does not conform to the HTML specification, it cannot be interpreted correctly by the browser.

As a rule, external JavaScript files have a. js extension. But this extension is not a virtual one, 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 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.

Note: MIME (Multipurpose Internet Mail Extensions) multi-purpose Internet Mail extension type.

The <script> element with the SRC attribute should not contain additional JavaScript code between its <script></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 point to the URL of a domain outside the domain of the current HTML page. But it's not safe.

Regardless of the code, as long as the defer and async properties do not exist, the browser parses the <script> elements sequentially in the order they appear in the page. That is, after the first <script> element contains the code parsing is complete, the second <script> contains the amount of code will be parsed, then the third, the fourth ...

2.1.1 The location of the label

By convention, all <script> elements should be placed in the

<! DOCTYPE html>

<title>example HTML page</title>

<script type= "Text/javascript" src= "Example.js" ></script>

<script type= "Text/javascript" src= "Example2.js" ></script>

<body>

<!--page Content--

<body>

This means that you must wait until all JavaScript code has been downloaded, parsed, and executed before you can start rendering the contents of the page (the browser renders the content when it encounters the <body> tag). For pages with a large amount of JavaScript code, there is a noticeable delay in rendering the page, and the browser window will be blank during the delay. Therefore, modern Web applications generally place all JavaScript references behind the contents of the page in the <body> element, for example:

<! DOCTYPE html>

<title>example HTML page</title>

<body>

<!--page Content--

<script type= "Text/javascript" src= "Example.js" ></script>

<script type= "Text/javascript" src= "Example2.js" ></script>

<body>

2.1.2 Delay Script

HTML4.01 defines the defer property for the <script> tag. Indicates that the script does not affect the construction of the page when it executes. 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>

<title>example HTML page</title>

<script type= "Text/javascript" defer= "defer" src= "Example.js" ></script>

<script type= "Text/javascript" defer= "defer" src= "Example2.js" ></script>

<body>

<!--page Content--

<body>

Some browsers ignore this property and handle the script as usual. For this reason, placing the deferred script at the bottom of the page is still the best option.

2.1.3 Asynchronous script

HTML5 defines the async attribute for the <script> element. This property is similar to the Defer property, 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>

<title>example HTML page</title>

<script type= "text/javascript" async src= "Example.js" ></script>

<script type= "text/javascript" async defer= "defer" src= "Example2.js" ></script>

<body>

<!--page Content--

<body>

In the above code, the second script may be executed before the first script file. Therefore, it is important to be independent of each other. The purpose of specifying the async attribute is to not allow the page to wait for two scripts to be downloaded and executed to asynchronously load other content on the page. 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 include Firefox3.6, SAFARI5, and Chrome.

In the XHTML document, set the Async property to Async= "Async".

The use of 2.1.4 in XHTML

In XHTML, the less-than sign in the comparison statement A<b < in XHTML will be treated as a starting new label to parse. The workaround:

1> replaces all of the less than sign < in the code with the corresponding HTML entity (&lt;).

2> uses CDATA fragments to contain JavaScript code.

2.2 Embed code with external files

Rather than being proud of embedding code, external files have the following advantages:

1> maintainability, storing JS files in a separate folder allows you to focus on editing JavaScript code without touching the HTML tags.

2> cacheable, the browser is able to cache all external JavaScript files linked according to the specific settings.

3> adapting to the future: using external files to contain JavaScript requires no use of the XHTML or annotation hack mentioned earlier. The syntax for HTML and XHTML to contain external files is the same.

2.3 Document Mode

Document modes include promiscuous mode and standard mode. Although these two patterns primarily affect the rendering of CSS content, in some cases it can also affect the interpretation of JavaScript execution. If a document type declaration is not found at the beginning of the documentation, all browsers will turn on promiscuous mode by default. But this is not a recommended practice, because different browsers behave differently in this mode, and cross-browser behavior is simply not consistent if some hack technology is not used.

Document mode for HTML 5 (Standard mode)

<! DOCTYPE html>

2.4 <noscript> Elements

Use the <noscript> element to specify alternative content that is displayed in browsers that do not support scripting. However, when scripting is enabled, the browser does not display any content of the <noscript> element.

Using JavaScript in HTML

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.