Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Script Tag
2.1.
Attributes of Script Tag
3.
Efficiently Script Loading
3.1.
A Solution to Delayed Loading
4.
Async and Defer
5.
Async Vs Defer
6.
Use Cases of Async and Defer
7.
Frequently Asked Questions
7.1.
Is it possible to use both async and defer simultaneously?
7.2.
On a script tag, what do the async and defer properties do?
7.3.
Is it better to use async or defer?
7.4.
What is the async attribute's default value?
7.5.
Is it true that async is faster than defer?
8.
Conclusion
Last Updated: Mar 27, 2024

Async and Defer Attributes in Javascript

Author Lekhika
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

We can use scripts to dynamically and interactively expand HTML texts. Scripts can be evaluated as document loads in order to dynamically change the document's contents.

The script tag is an important HTML tag. It refers to data or executable code that runs on a web page. The script tag consists of several attributes; async and defer are the attributes of the script tag.

In this article, we will discuss async and defer attributes. Before going to the attributes, let’s first understand what a script tag is.

Script Tag

The client-side script, such as Javascript, is specified using the HTML script tag. It allows you to insert a script into your HTML document.

Image manipulation, form validation, and dynamic content are all done with Javascript.

The following is the script tag syntax:

<script>
/code to be executed
</script>

Attributes of Script Tag

The main attributes of the Script tag are as follows:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Efficiently Script Loading

Scripts are generally "heavier" than HTML on modern websites: their download size is more extensive, and their processing time is longer.

When loading a script on an HTML page, you must take care not to degrade the page's loading performance. The loading time of an HTML page is affected by where and how you include your scripts.

The following is how we usually have a script on a page:

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

When the HTML parser encounters this line, it sends a request to fetch the script, which is then executed.

Once this is complete, the parsing can resume, and the user can examine the remaining HTML.

As you may expect, this process significantly impacts the page's loading time.

If the script takes longer than expected time to load, such as if the network is slow, the visitor will most likely see a blank page until the script is loaded and executed.

A Solution to Delayed Loading

We're taught that script tags occur in the <head> tag when learning HTML.

When the parser detects the script's line, it fetches the script and executes it, which we saw earlier. Then, once this process is completed, it parses the body element.

Placing the script tag in the head section is problematic since it introduces a significant delay. A typical solution to this problem is to place the script tag immediately before the closing /body> tag at the bottom of the page.

This is the best option If you need to support older browsers that don't keep two relatively new HTML features: async and defer.

Async and Defer

Defer and async are both boolean attributes of the Script tag. We can use them in the same way:

For Async:

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

Async is derived from the word 'asynchronous,' which refers to events that do not occur at the same time.

When you add async to a script tag, it becomes a boolean script attribute. It sends the following message to the browser:

  • When the HTML file comes into touch with the script, it should not be blocked from parsing. The DOM is still being built by the browser. Thus the items after the script tag are visible.
  • To run the script after it has been loaded in the background. Scripts with the async property do not wait for DOMContentLoaded to complete before running.
  • DOMContentLoaded events are not blocked by async.
  • Async scripts frequently follow the load-first principle.

Here is an example of async used as the Script attribute:

<p>...The content before scripts...</p>
    <script>
    document.addEventListener(‘DOMContentLoaded’, () => alert(“DOM is ready!”));
    </script>
    <script async src=”long-index.js”></script>
    <script async src="short-index.js"></script>
<p>...The content after scripts...</p>

For Defer:

<script defer src="index.js"> ………….. </script>

When a script tag like the one above contains defer, the browser receives the following notification:

  • When the HTML file comes into touch with the script, it should not be blocked from parsing. The DOM is still being built by the browser. Thus the items after the script tag are visible.
  • The script will be loaded in the background.
  • To prevent DOMContentLoaded events from occurring until the script has been fully loaded and evaluated.
  • To run scripts in a specific order. It keeps script tags in their proper order.

Here is an example of defer used as a script attribute:

<p>...The content before scripts...</p>
    <script>
    document.addEventListener(‘DOMContentLoaded’, () => alert(“DOM is visible after defer!”));
    </script>
    <script defer src=”long-index.js”></script>
    <script defer src="short-index.js"></script>
<p>...The content after scripts...</p>

 If both are specified, async takes precedence on current browsers, whereas older browsers that allow defer but not async will use defer.

These properties are only applicable when the script is used in the head section of the page; they are meaningless when the script is used in the body footer, as we saw previously.

You can compile with the help of Online Javascript Compiler for better understanding.

Async Vs Defer

The differences between async and defer attributes are as follows:

Use Cases of Async and Defer

It's challenging to know when to utilise async and when to use defer. We can, however, utilise defer when:

  • The script is dependent on the entire DOM.
  • When your script relies on another script, such as when jQuery or other external libraries or frameworks are used. Before starting your script, call the external library or framework.
  • When the order in which scripts are executed is critical.

We can use Async in the following situations:

  • Ads or Google Analytics are examples of scripts that are not dependent on the DOM. One can use async here.
  • In other cases, such as advertisements, the relative execution order of scripts is irrelevant.

Frequently Asked Questions

Is it possible to use both async and defer simultaneously?

Yes, you can use both attributes. However, you must choose between defer and async.

 

On a script tag, what do the async and defer properties do?

The boolean attributes async and defer are essentially two elements for the <script> tag. Async allows scripts to be run asynchronously as soon as they've been downloaded. Defer allows you to delay execution until the entire page has been parsed. 

 

Is it better to use async or defer?

Defer ensures that script execution coincides with or after Async. Scripts are probably made Defer or Async because they are less important for the page's critical content. As a result, it's preferable to use Defer so that they can be executed outside of the primary rendering time.

 

What is the async attribute's default value?

The async attribute takes a boolean value as an argument and defaults to true.

 

Is it true that async is faster than defer?

Yes, async is sometimes better than defer, and sometimes it isn't. We can easily verify this by comparing the time it takes for the event/s users care about to occur versus using async or defer.

Conclusion

This article extensively discussed the Script tagthe async and defer attributes, use cases, and Examples. We also discussed the difference between async and defer attributes.

We hope this blog has helped you enhance your knowledge regarding Script attributes. You can learn more about Javascript by visiting the article on free JavaScript Tutorial by Coding Ninjas. You can also learn how to create a Quiz app using JavaScript. 

Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations, and much more!!

We wish you Good Luck! Keep coding and keep reading Ninja!!

 

Live masterclass