Using the <script> Element to Link External Files

Site: Saylor Academy
Course: PRDV401: Introduction to JavaScript I
Book: Using the <script> Element to Link External Files
Printed by: Guest user
Date: Saturday, May 18, 2024, 8:28 PM

Description

The second way is to place JavaScript code in an external file and import it into the document. The second method is preferred because, with large programs, it is hard to maintain everything in an HTML document. JavaScript files have the file extension ".js". An example is:

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

Although all JavaScript code should be in a .js file because our programs are short, we'll place code directly within a <script> tag. We'll use external .js files in the next course.

<script>: The Script element

The <script> HTML element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The  <script> element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON.

Content categories Metadata content, Flow content, Phrasing content.
Permitted content Dynamic script such as text/javascript.
Tag omission None, both the starting and ending tag are mandatory.
Permitted parents Any element that accepts metadata content, or any element that accepts phrasing content.
Implicit ARIA role No corresponding role
Permitted ARIA roles No role permitted
DOM interface HTMLScriptElement


Source: Mozilla, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

Attributes

This element includes the global attributes.

async

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.

For module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available.

This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse. defer has a similar effect in this case.

This is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

See Browser compatibility for notes on browser support. See also Async scripts for asm.js.

crossorigin
Normal script elements pass minimal information to the window.onerror for scripts which do not pass the standard CORS checks. To allow error logging for sites which use a separate domain for static media, use this attribute. See CORS settings attributes for a more descriptive explanation of its valid arguments.
defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.

This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

The defer attribute has no effect on module scripts ' they defer by default.

Scripts with the defer attribute will execute in the order in which they appear in the document.

This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse. async has a similar effect in this case.

Warning: This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

Scripts with the defer attribute will execute in the order in which they appear in the document.

This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse. async has a similar effect in this case.

The defer attribute has no effect on module scripts - they defer by default.

integrity
This attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. See Subresource Integrity.
nomodule
This Boolean attribute is set to indicate that the script should not be executed in browsers that support ES2015 modules in effect, this can be used to serve fallback scripts to older browsers that do not support modular JavaScript code.
nonce
A cryptographic nonce (number used once) to allow scripts in a script-src Content-Security-Policy. The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial.
referrerpolicy
Indicates which referrer to send when fetching the script, or resources fetched by the script:
      • no-referrer: The Referer header will not be sent.
      • no-referrer-when-downgrade: The  Referer header will not be sent to origins without TLS (HTTPS).
      • origin: The sent referrer will be limited to the origin of the referring page: its scheme, host, and port.
      • origin-when-cross-origin: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
      • same-origin: A referrer will be sent for same origin, but cross-origin requests will contain no referrer information.
      • strict-origin: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
      • strict-origin-when-cross-origin (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
      • unsafe-url: The referrer will include the origin and the path (but not the fragment, password, or username).  This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.

Note: An empty string value ("") is both the default value, and a fallback value if referrerpolicy is not supported. If referrerpolicy is not explicitly specified on the <script> element, it will adopt a higher-level referrer policy, i.e. one set on the whole document or domain. If a higher-level policy is not available, the empty string is treated as being equivalent to  strict-origin-when-cross-origin.

src

This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document.

type

This attribute indicates the type of script represented. The value of this attribute will be in one of the following categories:

    • Omitted or a JavaScript MIME type: This indicates the script is JavaScript. The HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type. In earlier browsers, this identified the scripting language of the embedded or imported (via the src attribute) code. JavaScript MIME types are listed in the specification.
    • module: Causes the code to be treated as a JavaScript module. The processing of the script contents is not affected by the  charset and  defer attributes. For information on using module , see our JavaScript modules guide. Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching.
    • Any other value: The embedded content is treated as a data block which won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. The  src attribute will be ignored.

Deprecated attributes

charset If present, its value must be an ASCII case-insensitive match for "utf-8". It’s unnecessary to specify the charset attribute, because documents must use UTF-8, and the script element inherits its character encoding from the document.

language Like the type attribute, this attribute identifies the scripting language in use. Unlike the type attribute, however, this attribute’s possible values were never standardized. The type attribute should be used instead.

Notes

Scripts without async , defer or type="module" attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page.

The script should be served with the text/javascript MIME type, but browsers are lenient and only block them if the script is served with an image type (image/*); a video type (video/*); an audio (audio/*) type; or text/csv. If the script is blocked, an error is sent to the element, if not a load event is sent.

Examples

Here are a few examples.

Basic usage

These examples show how to import (an external) script using the <script> element.

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

And the following examples show how to put (an inline) script inside the <script> element.

<script>
  alert("Hello World!");
</script>

Module fallback

Browsers that support the module value for the type attribute ignore any script with a nomodule attribute. That enables you to use module scripts while also providing nomodule-marked fallback scripts for non-supporting browsers.

<script type="module" src="main.js"></script>
<script nomodule src="fallback.js"></script>

Embedding data in HTML

You can also use the <script> element to embed data in HTML with server-side rendering by specifying a valid non-JavaScript MIME type in the type attribute.

<!-- Generated by the server -->
<script id="data" type="application/json">{"userId":1234,"userName":"John Doe","memberSince":"2000-01-01T00:00:00.000Z"}</script>
<!-- Static -->
<script>
 const userInfo = JSON.parse(document.getElementById("data").text);
 console.log("User information: %o", userInfo);
</script>