How to use the <script>
tag in HTML
The <script>
tag is used to define a client-side script, such as a JavaScript. It can be used to execute JavaScript code within an HTML document.
To include JavaScript code in an HTML document, you can either write the code directly within the <script>
tag or link to an external script file. Here's an example of both methods:
Example of inline script:
<script>
document.getElementById("demo").innerHTML = "Hello, World!";
</script>
Example of linking to an external script file:
<script src="myscript.js"></script>
In the first example, the JavaScript code is written directly within the <script>
tag. In the second example, the script is linked to an external file called myscript.js
.
Main attributes of the <script>
tag:
Attribute | Description |
---|---|
src |
Specifies the URL of an external script file. |
type |
Specifies the MIME type of the script. Default value is "text/javascript". |
async |
Specifies that the script is executed asynchronously (only for external scripts). |
defer |
Specifies that the script is executed after the document has been parsed (only for external scripts). |
Here's an example of an external script file with the src
attribute:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
In this example, the jQuery library is loaded from an external URL using the src
attribute.
Remember to always include the closing tag </script>
at the end of the script code.