<script>

The HTML <script> element allows you to include executable JavaScript code in a webpage, enabling client-side scripting and dynamic features, or you can link to external JavaScript files.

<script> Tag

The <script> tag in HTML is used to include or link to JavaScript code within a webpage. It can contain inline JavaScript or reference an external file for dynamic functionality.

Syntax

index.html
<!-- Inline JavaScript -->
<script>
  // JavaScript code here
</script>

<!-- External JavaScript -->
<script src="path/to/script.js"></script>

Example

index.html
<script>
  document.getElementById("demo").innerHTML = "Hello, JavaScript!";
</script>

Definition and Usage

The <script> tag is used to embed or link to a client-side script, typically JavaScript. It can either include script code directly or reference an external script file using the src attribute.

JavaScript is commonly used for tasks like image manipulation, form validation, and dynamically updating content.

Attributes

AttributeValueDescription
asyncasyncDownloads and executes the script while the page is still being processed (only for external scripts)
crossoriginanonymous, use-credentialsDefines how the request should handle cross-origin sharing (CORS)
deferdeferEnsures the script downloads while parsing continues but waits to execute until parsing is finished (only for external scripts)
integrityfilehashEnables browsers to verify that the fetched script remains unchanged from its original version
nomoduleTrue, FalsePrevents the script from executing in browsers that support ES2015 modules
referrerpolicyno-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-urlControls what referrer information is sent when requesting the script
srcURLSpecifies the location of an external script file
typescript typeDefines the media type of the script
Additionally, consider using the <noscript> element for users who have disabled scripts in their browser or are using a browser that doesn't support client-side scripting.

HTML vs. XHTML Differences

In XHTML, script content is treated as #PCDATA instead of CDATA, meaning special characters are processed as part of the document.

As a result, in XHTML:

  • Special characters must be properly encoded.
  • Alternatively, script content can be enclosed within a CDATA section to prevent parsing errors.

Default CSS Settings

In most web browsers, the <script> element is rendered using the following default settings:

style.css
script {
  display: none;
}

Conclusion

The <script> tag in HTML is used to embed or link JavaScript code to create dynamic, interactive functionality on web pages. It can either contain inline JavaScript or reference an external script using the src attribute. Attributes like async and defer help control script execution.