<script>
<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
<!-- Inline JavaScript -->
<script>
// JavaScript code here
</script>
<!-- External JavaScript -->
<script src="path/to/script.js"></script>
Example
<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.
Attributes
Attribute | Value | Description |
---|---|---|
async | async | Downloads and executes the script while the page is still being processed (only for external scripts) |
crossorigin | anonymous, use-credentials | Defines how the request should handle cross-origin sharing (CORS) |
defer | defer | Ensures the script downloads while parsing continues but waits to execute until parsing is finished (only for external scripts) |
integrity | filehash | Enables browsers to verify that the fetched script remains unchanged from its original version |
nomodule | True, False | Prevents the script from executing in browsers that support ES2015 modules |
referrerpolicy | no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url | Controls what referrer information is sent when requesting the script |
src | URL | Specifies the location of an external script file |
type | script type | Defines the media type of the script |
<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:
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.
<base>
The HTML <base> element sets a base URL for resolving all relative links and resources within a document, providing a reference point for those URLs.
<noscript>
The HTML <noscript> element provides fallback content for users with JavaScript disabled or unsupported, ensuring critical information or features remain accessible.