2 JavaScript in HTML

1 The <script> Element

The primary method of inserting JavaScript into an HTML page is via the <script> element. This element was created by Netscape and first implemented in Netscape Navigator 2. It was later added to the formal HTML specification. There are six attributes for the <script> element:

  • async—Optional. Indicates that the script should begin downloading immediately but should not prevent other actions on the page such as downloading resources or waiting for other scripts to load. Valid only for external script files.
  • charset—Optional. The character set of the code specified using the src attribute. This attribute is rarely used because most browsers don’t honor its value.
  • crossorigin—Optional. Configures the CORS settings for the associated request; by default, CORS is not used at all. crossorigin="anonymous" will configure the request for the file to not have the credentials flag set. crossorigin="use-credentials" will set the credentials flag, meaning the outgoing request will include credentials.
  • defer—Optional. Indicates that the execution of the script can safely be deferred until after the document’s content has been completely parsed and displayed. Valid only for external scripts. Internet Explorer 7 and earlier also allow for inline scripts.
  • integrity—Optional. Allows for verification of Subresource Integrity (SRI) by checking the retrieved resource against a provided cryptographic signature. If the signature of the retrieved resource does not match that specified by this attribute, the page will error and the script will not execute. This is useful for ensuring that a Content Delivery Network (CDN) is not serving malicious payloads.
  • language—Deprecated. Originally indicated the scripting language being used by the code block (such as “JavaScript”, “JavaScript1.2”, or “VBScript”). Most browsers ignore this attribute; it should not be used.
  • src—Optional. Indicates an external file that contains code to be executed.
  • type—Optional. Replaces language; indicates the content type (also called MIME type)
    of the scripting language being used by the code block. Traditionally, this value has always
    been “text/javascript”, though both “text/javascript” and “text/ecmascript” are
    deprecated. JavaScript files are typically served with the “application/x-javascript”
    MIME type even though setting this in the type attribute may cause the script to be
    ignored. Other values that work in non–Internet Explorer browsers are “application/
    javascript” and “application/ecmascript”. If the value is module, the code is treated as
    an ES6 module and only then is eligible to use the import and export keywords.

There are two ways to use the <script> element: embed JavaScript code directly into the page or include JavaScript from an external file.

To include inline JavaScript code, place JavaScript code inside the <script> element directly, as follows:

<script>
 	function sayHi() {
 		console.log("Hi!");
 	}
</script>

The JavaScript code contained inside a <script> element is interpreted from top to bottom. In the case of this example, a function definition is interpreted and stored inside the interpreter environment. The rest of the page content is not loaded and/or displayed until after all of the code inside the <script> element has been evaluated.

When using inline JavaScript code, keep in mind that you cannot have the string "</script>" anywhere in your code. For example, the following code causes an error when loaded into a browser

<script>
 	function sayScript() {
 		console.log("</script>");
 	}
</script>

Because of the way that inline scripts are parsed, the browser sees the string "</script>" as if it were the closing </script> tag. This problem can be avoided easily by escaping the “/” character, as in this example:

<script>
 	function sayScript() {
 		console.log("<\/script>");
 	}
</script>

The changes to this code make it acceptable to browsers and won’t cause any errors.

To include JavaScript from an external file, the src attribute is required. The value of src is a URL linked to a file containing JavaScript code, like this:

<script src="example.js"></script>

In this example, an external file named example.js is loaded into the page. The file itself need only contain the JavaScript code that would occur between the opening <script> and closing </script>tags. As with inline JavaScript code, processing of the page is halted while the external file is interpreted. (There is also some time taken to download the file.) In XHTML documents, you can omit the closing tag, as in this example:

<script src="example.js"/>

This syntax should not be used in HTML documents because it is invalid HTML and won’t be handled properly by some browsers, most notably Internet Explorer.

NOTE
By convention, external JavaScript files have a .js extension. This is not a requirement because browsers do not check the file extension of included JavaScript files. This leaves open the possibility of dynamically generating JavaScript code using a server-side scripting language, or for in-browser transpilation into JavaScript from a JavaScript extension language such as
TypeScript or React’s JSX. Keep in mind, though, that servers often use the file extension to determine the correct MIME type to apply to the response. If you don’t use a .js extension, double-check that your server is returning the correct MIME type.

It’s important to note that a <script> element using the src attribute should not include additional JavaScript code between the <script> and </script> tags. If both are provided, the script file is downloaded and executed while the inline code is ignored.

One of the most powerful and most controversial parts of the <script> element is its ability to include JavaScript files from outside domains. Much like an <img> element, the <script> element’s src attribute may be set to a full URL that exists outside the domain on which the HTML page exists, as in this example:

<script src="http://www.somewhere.com/afile.js"></script>

When the browser goes to resolve this resource, it will send a GET request to the path specified in the src attribute to retrieve the resource—presumably a JavaScript file. This initial request is not subject to the browser’s cross-origin restrictions, but any JavaScript returned and executed will be. Of course, this request is still subject to the HTTP/HTTPS protocol of the parent page.

Code from an external domain will be loaded and interpreted as if it were part of the page that is loading it. This capability allows you to serve up JavaScript from various domains, if necessary. Be careful, however, if you are referencing JavaScript files located on a server that you don’t control. A malicious programmer could, at any time, replace the file. When including JavaScript files from a different domain, make sure you are the domain owner or the domain is owned by a trusted source.
The <script> tag’s integrity attribute gives you a tool to defend against this; however, it has limited browser support.

Regardless of how the code is included, the <script> elements are interpreted in the order in which they appear in the page so long as the defer and async attributes are not present. The first <script> element’s code must be completely interpreted before the second <script> element begins interpretation, the second must be completed before the third, and so on.

Tag Placement
Deferred Scripts
Asynchronous Scripts
Dynamic Script Loading
Changes in XHTML
Deprecated Syntax
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值