HTML <script> Tag Tutorial - Usage, Syntax,
Attributes and Example

calender-iconPublished: 11 May 2025

clock-icon5-min read





INTRODUCTION

The <script> element is used to embed executable code/data in the webpage. This element is generally used to embed javascript code but can be used with other programming language and JSON data.

Syntax:

<script>--executable code--</script>

ATTRIBUTES

The attributes that be used with <script> element are listed below.

  • async
  • defer
  • blocking
  • crossorigin
  • fetchpriority
  • integrity
  • nomodule
  • nonce
  • referrerpolicy
  • src
  • value


1. async

Javascript is a parser-blocking resource. When browser loads HTML and encounters <script> tag it stops parsing HTML. It executes the scripts first. In case of external script, it downloads the script, then execute it and only after that it can continue with HTML parsing.

The async attribute makes the script to be downloaded in parallel to parsing. It is executed as soon as it is available. While script execution HTML parsing is paused.

In case of multiple scripts with async attribute, the scripts don't execute in any particular order. The script downloaded first is executed first.

It is a boolean attribute hence when it is present it represents true value and when absent it represents false value.

Example:

<script async src="./myscript.js"></script>

2. defer

The defer attribute also makes the script parser non-blocking. The script is downloaded in parallel to parsing and but is executed only after HTML parsing is completed. Hence scripts never block the parsing.

Scripts with defer attribute are executed in the order in which they appear in webpage. Order may be important when later script depends on the first script. If both the defer and async attribute are specified then defer will be ignored as async has higher priority.

Example:

<script defer src="./myscript.js"></script>

3. blocking

This attribute specifies that certain operations should be blocked on downloading the script. The operations must be a space separated list of blocking tokens.

Example: In the below example the rendering of content is blocked.


<link rel="stylesheet" href="./styles.css" blocking="render" >
4. crossorigin

The crossorigin attribute provides support for CORS. Cross-Origin Resource Sharing(CORS) is a mechanism that allows server to specify any origins (meaning external server/website) other that itself from which browser is permitted to access resources. For security reasons Browsers restrict cross-origin requests

This attribute defines whether user credentials should be sent during CORS request. User Credentials are generally cookies, TLS client certificates or HTTP authentication header containing username and password. By default, these credentials are not sent in Cross-Origin request which makes a site vulnerable to Cross-site Request Forgery. The possible values of this attribute are listed below.

  • anonymous: Cross-Origin request is performed without user-credentials.
  • use-credentials: Cross-Origin request is performed using user-credentials.
  • If this attribute is not present the resource is fetched without CORS request.
  • If the value of this attribute is invalid, then it resolves to anonymous.

Example:

<script src="example.com/example.js"  crossorigin="anonymous"></script>

5. fetchpriority

This attribute is used to specify to the browser, download priority for resource. The Possible values are listed below.

  • high - This value assigns a higher priority to a resource relative to other resources.
  • low - This value assigns a lower priority to a resource relative to other resources.
  • auto - It is used when you don't want to set a preference for this attribute. This is the default value. If no value or invalid value is specified then this option is used

Example:


<link rel="stylesheet" href="styles.css" fetchpriority="high">
6. integrity

This attribute contains the cryptographic hash of the script. Hash is a digital signature of data which is generated using cryptographic hash function. The browser can use this to verify whether the downloaded script is manipulated or not. This attribute can only be used when src attribute is not specified.


<link rel="stylesheet" href="my_stylesheet.css" integrity="sha256-10c1f22695d2e67cc2dd47baa775da0ea84d4101ab9eb3e733f30e5010b671b7">
7. nomodule

This boolean attribute specifies that script should not be executed in browsers that support ES-Modules. ES-Module is a way to organise javascript code into modules. So complex projects are splitted into separate modules that can be downloaded when needed.

The modern browser recognise <script type="module"> and will execute the script. It also understands the nomodule attribute and doesn't load <script nomodule type="text/javascript"> script.

The Legacy/old browser will ignore the <script type="module"> script because is an unknown type. The browser ignores the nomodule attribute beacuse it is also of unknown type and loads the script because it will recognise type="text/javascript" in the script (<script nomodule type="text/javascript">).

<script nomodule src="./myscript.js"></script>
8. nonce

Content-security-policy (CSP) is an HTTP header added to webpage which controls what resource an webpage is allowed to load and from which origin. The policy is specified as directive list shown in example below. But this list-based policy is vulnerable to cross-site-scripting hence an attacker can inject malicious script into website. To overcome this Content-Security-Policy based on nonce or hash is used.


<Content-Security-Policy: img-src sample.com>

Nonce is a random number which acts as a unique identifier for a specific <script> element. It marks the <script> tag as trusted. It can be used only once.

How Nonce works
  • In a nonce based CSP, a random number is generated at runtime.
  • This number is set as value of <script-src> attribute of CSP.
  • The same value is also set as value of nonce attribute of <script> tag.
  • The Browser compares these two values and loads the script only if they are equal.

Content-Security-Policy:
  script-src 'nonce-random_number'


<script nonce={'random_number'} src="myscript.js"></script>

An attacker cannot run a malicious script because he does not know the value of correct nonce which is randomly generated. It is necessary that nonce must be different for every response and must not be predictable.

9. referrerpolicy

This attribute is used to specify the referrer when fetching a script or an external resource is fetched by script.

The referrer attribute is used to define the HTTP referrer header for the outgoing links from the current webpage.

The HTTP Referrer header contains the address of the previous page from which a request was made. It makes possible to identify the referring website. This header is commonly used for analytics, logging, access control and security purposes.

In the below example a user is on website-A and clicks on a link that points to website-B. The user's browser makes an HTTP request to the server of website-B. In this case the referrer is website-A. In the HTTP request, referrer header contains address of website-A.

http-referrer-header

The possible values this attribute can take are listed below.

  • no-referrer: Do not send HTTP referrer header.
  • origin: send only the origin of the webpage - scheme, host, port.
  • no-referrer-when-downgrade: When the destination webpage is atleast as secure as the current page (HTTPS to HTTPS ) send the full URL as referrer, and if its less secure (HTTPS to HTTP) send no referrer. This is the default option.
  • origin-when-cross-origin: when request comes from same-origin send full url and for other cases send only origin - scheme, host, port. (ex. Full url - https://example.com/page1 and )
  • same-origin: when request comes from same-origin send full url and for cross origin cases send no referrer.
  • strict-origin: Send the origin when destination has same security level (HTTPS to HTTPS) and for less secure destination send no referrer.
  • strict-origin-when-cross-origin: send full URL for same origin. Send only the origin when destination has same security level (HTTPS to HTTPS) and for less secure destination send no referrer.
  • unsafe-URL: whether request comes from same-origin or cross-origin send full url. This case is unsafe because it can leak origins and paths to insecure origins.
10. src

This attribute specifies the URL of external script.

11. type

This attribute specifies the type of script. The possible values of this attribute is listed below.

  • MIME Type - This attribute specifies the MIME type of script. ex. type="text/javascript".
  • importmap - In modern Javascript, code is divided into ES modules. This tag allows you to map module name with its corresponding URL using JSON making it easier to use modules. The below example will make it clear.

    
    <script type="importmap"> 
     {
      "imports": { 
       "module1": "./modules/module1.js", 
       "module2": "./modules/module2.js"   
     } 
    } 
    </script>

  • module - This value specifies that code is a javascript module.
  • Any other Value - If the value is not any of the above mentioned values then the embedded content is treated as data block and not processed by browser

Frequently Asked Questions (FAQ)

Where Should the <script> Tag Be Placed in HTML?
The placement of the <script> script tag depends on when you want the JavaScript to execute and how it affects page performance.
  • Best Place: at the bottom of <body> element which ensures that the page loads first before executing JavaScript.
  • It can be placed in <head> element with defer attribute if scripts need to run after HTML loads.
  • It can be placed in <head> element with async attribute for independent scripts like analytics.
  • You should avoid placing this tag in <head> element without defer or async to prevent blocking.

Is html a scripting language?
No, HTML (HyperText Markup Language) is NOT a scripting language. It is a markup language used to structure web content.

What is <script> in HTML?
The <script> tag in HTML is used to embed or link JavaScript code, which adds interactivity and dynamic behaviour to web pages.

What is the difference between the async and defer attributes in the <script> tag?
The <script> tag in HTML can have two important attributes for loading JavaScript: async and defer. Both controls how the script is downloaded and executed relative to the HTML parsing.

1. async (Asynchronous Loading) Attribute
The script downloads in parallel with HTML parsing. Once downloaded, it executes immediately, pausing HTML parsing. Best for independent scripts that don’t rely on the DOM.

2. defer (Deferred Loading) Attribute
The script downloads in parallel with HTML parsing. It waits until the entire HTML document is parsed before executing. Scripts with defer execute in order as they appear in the document. Best for DOM-dependent scripts.

How to add javascript to html?
  • Place your JavaScript code inside a <script> tag within the HTML file, usually before the closing </body> tag
  • Put your JavaScript code in a separate .js file and link it using the <script> tag with a src attribute

Why is it recommended to place a <script> tag at the end of the <body> tag rather than at the beginning?
  • The <script> is parser blocking, hence If the <script> tag is near the top of the page, this causes a delay in rendering the visible content. The page may appear blank longer to the user.
  • Scripts often manipulate or interact with DOM elements (like buttons, divs, etc.). If the script runs before the elements are loaded, it will fail (e.g., document.getElementById(...) returns null). Placing the script at the bottom ensures all elements are already parsed and available to JavaScript.

Is placing the <script> tag after the </body> tag incorrect?
According to the HTML specification: The <script> tag must be a child of either <head> or <body>, not outside of them. Placing it after </body> means it's outside the document structure, which makes it invalid HTML.

What is the use of the "nonce" attribute for script elements?
Content-security-policy (CSP) is an HTTP header added to webpage which controls what resource an webpage is allowed to load and from which origin. The policy is specified as directive list shown in example below. But this list-based policy is vulnerable to cross-site-scripting hence an attacker can inject malicious script into website. To overcome this Content-Security-Policy based on nonce or hash is used.

Nonce is a random number which acts as a unique identifier for a specific <script> element. It marks the <script> tag as trusted. It can be used only once.
  • In a nonce based CSP, a random number is generated at runtime.
  • This number is set as value of <script-src> attribute of CSP.
  • The same value is also set as value of nonce attribute of <script> tag.
  • The Browser compares these two values and loads the script only if they are equal.
An attacker cannot run a malicious script because he does not know the value of correct nonce which is randomly generated. It is necessary that nonce must be different for every response and must not be predictable.

What are the differences between including a script in the head and in the body of an HTML page?
1. Script in head
When script tag is in head, The browser stops parsing HTML to load and run the script. If the script tries to access elements (like document.getElementById()), it may fail because the elements haven’t been parsed yet.

2. Script at the End of body Placing the script at the bottom ensures all elements are already parsed and available to Script. Also, it Doesn't block page rendering.