The <script> Tag

The <script> Tag

The <script> tag in the HTML page contains the executable script or the source to the executable script.

We will learn about three attributes in the <script> tag with their meaning and execution behavior.

  • src ๐Ÿ˜‚
  • async
  • defer

Src

<script src="./script.js"></script>

The src attribute contains the link to the external javascript file. It may be your own written code or maybe any library you want to use.

Async

<script async src="./script.js"></script>

The presence of async attributes tells the browser to execute the code when the page is parsing.

For instance, check the example.

index.html

<html>
<head>
    <title>The Script Tag - Javascript 1o1</title>
</head>
<body>

</body>
<script async src="./script.js"></script>
<script>
    console.log("This will be executed first");
</script>
</html>

script.js

console.log("This will be executed second")

This page will create such output output1.png

Even though the script.js is fetched first, it will not start executing. The script.js will start executing parallelly with the parsing of the fetched HTML.

Defer

The defer attribute shows similar behavior as the async attribute. But script tag with defer attribute starts executing the script after completion of parsing the page.

index.html

<html>
<head>
    <title>The Script Tag - Javascript 1o1</title>
</head>
<body>

</body>
<script defer src="./script.js"></script>
<script>
    console.log("This will be executed first");
</script>
</html>

script.js

console.log("This will be executed second")

This page will create such output output1.png

Although defer and async usage produced similar output. It may produce an error if not used according to its own requirements.

The external library should never be used with defer attributes as our script may use the API of the external library, it will throw ReferenceError

The defer attributes have no effect on inline scripts. and should only be used when the src attribute is present.

DeferAsync
executes scripts after completion of parsing pageexecutes scripts parallel with parsing page

If neither defer nor async attribute is present. The script will be fetched and executed immediately.