You may want to add JavaScript files, third-party libraries, or frameworks to your web pages. In this case, knowing how to make these additions quickly will be essential. The HTML script tag can help.
This powerful tag feature enables developers to effortlessly include common libraries, plugins, and scripts into their HTML documents to increase performance. Not only does this enhance development speed, but it also promotes better debugging and smoother collaboration with other coders.
Read on to learn more about what the <script> tag is and what it does.
Table of Contents
- What is the script tag in HTML?
- Script Tag Attributes
- HTML Script Tag Examples
You can insert a JavaScript file or any other scripting language into an HTML document with the help of <script> tags. This code may be placed directly within the tag, or you may use an external file and reference it through the src attribute to reduce repeated coding and optimize for better performance.
When the HTML document is loaded, the browser parses and executes the script, adding dynamic behavior and interactivity to the page. For example, you can use JavaScript to respond to user actions, update content, and create animations.
By including the <script> tag in the header or body of an HTML document, you can control various features such as asynchronous and deferral, which can direct scripts to run orders.
Additionally, the src attribute allows you to determine external resources for your script code while remaining highly customizable.
Now let’s check out some popular script tag attributes.
Script Tag Attributes
The script tag has many attributes you can use to control how the code is loaded and executed. These attributes include:
- Where to put the script tag in the HTML.
- What it does (asynchronously, deferring loading, etc.).
- What priority it should have when fetched by the browser.
- Which cryptographic hash should be used for verification.
- And, whether blocking or nonce is enabled.
All these attributes serve different purposes and help keep your website performant and secure. Below are some of the most used script tag attributes.
Async
This attribute is a boolean that returns true if it’s present. The async attribute informs the browser to load this script asynchronously so that once downloaded, the page will be rendered without interference. As a result, you can delight in speedy performance.
Crossorigin
The crossorigin attribute is a valuable asset when loading scripts from different domains. By default, the browser will not transfer certain information in the error messages sent to window.onerror for scripts sourced from external domains.
In using this attribute, however, you can enable logging of any errors generated by these types of requests, allowing for better performance and an improved user experience across all pages on your website.
Defer
With this attribute in place, the browser will wait until the entire page has been parsed before executing any script. This is especially useful if you have several scripts on a single page, as it guarantees that they are carried out as per their order of appearance in HTML code.
Refrain from using this attribute if you won’t be including the src attribute, as this will cause the inline scripts to be ineffective.
Fetch Priority
This feature allows you to prioritize the script source when retrieved by the web browser for higher performance. The priority of requests can be adjusted based on a variety of influences, such as the size and number of resources requested at one time in addition to network conditions:
- High. This signal signifies a high-priority call for external scripts and should take precedence over other fetch requests.
- Low. Signals are fetched with less priority than other external scripts.
- Auto. By default, signals determine the fetch priority of external scripts compared to other ones automatically.
Integrity
With this capability, you can give the browser a cryptographic hash of the script resource to verify that no one changed it while downloading. This ensures your script is properly protected and safe to use.
Nomodule
Recently incorporated into HTML5, the nomodule attribute of the <script> tag provides a way for developers to indicate that modern browsers should not execute their script. This is especially useful if your code does not follow ECMAScript module standards and only needs to run on older web browsers.
Nonce
Nonce means the number used once. This feature allows you to create an unpredictable, one-time-use string (known as a “nonce”) that confirms the script has not been altered during download.
This unique identifier is then included in your response's Content Security Policy header and verified by any web browser used. With this security measure in place, you can be confident no malicious changes have occurred throughout the transmission process.
Referrerpolicy
With this feature, you can set the Referrer-Policy header of the response that controls how any reference information is sent when requesting a script.
- no-referrer: No Referer header will be transmitted.
- no-referrer-when-downgrade: If an origin does not have Transport Layer Security (TLS, also known as HTTPS), the Referer header will not be sent.
- origin: The referrer sent to the server will be restricted solely to its source: including protocol, hostname, and port.
- origin-when-cross-origin: As a precaution, the referrer sent to external sources will only include the scheme, host name, and port number. However, when navigating internally on the same origin page, it will also list its path.
- same-origin: Requests made within the same domain will include a referrer. However, requests across different domains won't have any associated referrer data.
- strict-origin: When moving from a secure protocol (HTTPS) to another secure destination, ensure that the document's origin is sent as part of the referrer; however, do not send it if transitioning to an insecure environment (HTTPS→HTTP).
- strict-origin-when-cross-origin: Whenever making a same-origin request, always provide the full URL. Only send the origin if both destinations have the same security level (e.g., HTTPS→HTTPS). Lastly, omit any header when accessing a less secure website (for example, HTTPS→HTTP).
- unsafe-URL: The referrer will include the origin and path, though it omits fragment, password, and username. This value is unsafe, exposing origins and paths from secure TLS sources to unsecured places.
Src
This attribute defines the exact location of an external script resource that needs to be loaded. Rather than including a script directly into your document, this is a great alternative.
Type
This attribute specifically defines the type of script, typically as text/javascript. The type attribute is necessary to provide the browser with a clear understanding of handling your scripts.
Omitting this attribute or setting it as an empty string or JavaScript MIME type will automatically tell the browser that your script contains classic JavaScript code — making it extra interpretable and easier for processing.
Blocking
This attribute is used to specify how the script should be loaded and executed. It blocks certain operations when the script is fetched.
Now that we’ve learned about script tag attributes, let’s check out a few examples.
HTML Script Tag Examples
1. Importing Script Using ‘Src’
Of course, you can include your JavaScript code in the same document as your HTML. However, you can also separate your code in a separate file and import the code using the script tag and the src attribute. Take a look at the example below to see how it’s done.
If you would like to include the script inline, check out the example below.
2. Script Tag Using ‘Defer’ Attribute
In the example below, you’ll see the script tag used within the document's body. This tag uses the defer attribute, which will defer the execution of the script until after the HTML has been rendered.
3. Script Tag Using ‘Integrity’ Attribute
Here is an example using an integrity attribute with a script tag.
The script tag includes a hash value in the integrity attribute to ensure the script has not been tampered with. The hash specified in the script tag will then be compared to the hash in the loaded script. If they match, the script will be deemed valid, loaded, and executed.
The cross-origin attribute is anonymous, allowing the script to be loaded from a different domain.
Getting started with the HTML Script Tag
Using the HTML script tag is an effective way to add scripts to your web pages. It provides a secure, reliable, and consistent method of loading content from external sources.
When using the script tag, make sure that you understand what each attribute means and how it affects your page’s performance so that you can make informed decisions about where to place scripts on your web pages. This will ensure they are loaded optimally and your website runs smoothly.