<script>
Integrates or links JavaScript scripts with an HTML page.
The <script>
tag is essential in HTML for integrating or linking JavaScript scripts to a web page. It allows you to add interactive or dynamic functionalities to a site.
Scripts included via this tag can be directly integrated into the HTML code or linked to an external JavaScript file, as we will see. 😉
Structure and syntax of the <script>
tag
Basic structure and syntax
The <script>
tag is a container tag. It is used with:
- An opening tag
<script>
; - A closing tag
</script>
.
It can contain JavaScript code directly or reference an external file via the src
attribute.
Here is its general structure:
HTML
<script src="[URL of the JavaScript file]"></script>
Usage examples
Integrating an external JavaScript script
To integrate an external JavaScript script, simply use the src
attribute with the URL:
HTML
<script src="script.js"></script>
Integrating a script directly
It is also possible to directly integrate JavaScript code within the tag, without an external file:
HTML
<script>
console.log('Welcome to our site!');
</script>
Attributes of the <script>
tag
Attribute | Description | Example |
---|---|---|
src | Specifies the path to an external JavaScript file. | <script src="script.js"></script> |
type | Defines the MIME type of the script. By default, it is text/javascript . | <script type="module"></script> |
async | Loads the script in parallel and executes it immediately once loaded. | <script src="script.js" async></script> |
defer | Defers the execution of the script until the DOM is fully loaded. | <script src="script.js" defer></script> |
crossorigin | Handles cross-origin requests. Values: anonymous , use-credentials . | <script src="script.js" crossorigin="anonymous"></script> |
integrity | Allows verifying the integrity of a script with a cryptographic signature. | <script src="script.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8w"></script> |
Browser compatibility
Browser | Compatibility with <script> | Support for ES modules (type="module" ) |
---|---|---|
Chrome | Yes | Yes (from Chrome 61) |
Firefox | Yes | Yes (from Firefox 60) |
Safari | Yes | Yes (from Safari 10.1) |
Edge | Yes | Yes (from Edge 16) |
Internet Explorer | Yes | No |