Summary -
In this topic, we described about the <script> tag along with detailed example.
The <script> tag allows inserting scripts in the HTML document. In other words, the <script> tag is used to define client-side script such as the scripting languages like javascript etc,. Any scripting language can be used to insert into the HTML document.
The default value is text/javascript. The default value can be ignored if using JavaScript. Scripting can be used to manipulate content and to incorporate dynamic changes of content mostly.
Script inserted between the opening and closing tags. The <script> element either contains scripting statements, or an external script file through the src attribute.
src attribute will be used if importing the script from an external file. URL should be in between the quotes like <script type="" src=""></script>. If the "src" attribute is present, the <script> element must be empty.
The type attribute allows specifying the language of the script or format of the data. If async="async": The script is executed asynchronously with the rest of the page. If async is not present and defer="defer": The script is executed when the page has finished parsing.
If neither async or defer is present: The script is fetched and executed immediately. An executable script, such as JavaScript.
Internal Script Syntax -
<script type="">
Script coding here
</script>
External Script Syntax -
<script type="" src="URL"></script>
Async attribute in HTML5.
Optional Attributes -
Attribute | Description | Values |
---|---|---|
src | Specifies the location of external script files to be imported. | URL. |
type | Specifies the type of script. | Default is text/javascript. |
charset | Specifies character encoding of an external script. Used only when src is present. | A character encoding declaration such as UTF-8. |
async | Specifies that an external script should be executed asynchronously. Used only if src is present.HTML5 attribute | None. |
defer | Specifies that an external script should be deferred and executed only after the page has been parsed. Used only if src is present. | None. |
crossorigin | Specifies how to handle Cross Origin Resource Sharing requests. |
Example -
<!DOCTYPE html>
<html lang="en">
<head>
<title>Link Tag</title>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
<script async src="tc.js"></script>
</head>
<body>
<!-- Content of the HTML document -->
<button onclick="myFunction()">Click here</button><br><br>
<p class="demo"></p>
</body>
</html>