DEV Community

Cover image for Javascript 1o1 - The Script Tag
Anjal Binayak Adhikari
Anjal Binayak Adhikari

Posted on

Javascript 1o1 - The Script Tag

This article was originally posted on my hashnode blog

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

script.js

console.log("This will be executed second")
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

script.js

console.log("This will be executed second")
Enter fullscreen mode Exit fullscreen mode

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.

Defer Async
executes scripts after completion of parsing page executes scripts parallel with parsing page

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

Top comments (0)