Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 5036

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 27, 20242024-11-27T05:30:08+00:00 2024-11-27T05:30:08+00:00

Boost Page Speed with async and defer

  • 61k

JavaScript is an essential component in web programming, enabling interactivity and dynamic behaviour on web pages. While HTML and CSS handle the structure and aesthetics, JavaScript brings the page to life.

There are different ways to add JavaScript code to an HTML file. The most common method is to store the JavaScript code in a separate file with a .js extension. Then, you can load that file into the HTML using the script tag. This allows the browser to download and execute the JavaScript code.

<!DOCTYPE html> <html> <head>     <meta charset="UTF-8">     <title>Your Page Title</title>     <script src="your-script.js"></script> </head> <body>     <!-- Content of your webpage goes here --> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

The issue with loading a JavaScript file in the <head>

When a browser encounters a <script src='...'>...</script> tag in HTML, it pauses building the webpage and immediately executes the script. The browser must wait for the script to download, execute it, and only then can it continue processing the rest of the page.

Rendering without any attributes

This leads to 2 significant problems:

  1. Scripts cannot interact with or modify elements that appear after them in the HTML code. This means they can't add event handlers or make changes to elements lower down the page.
  2. If there is a large script at the top of the page, it causes a delay in displaying the page content. Users have to wait for the script to download and run before they can see the actual content of the page.

The Dirty Workaround:

So how do we fix this problem? One obvious but not-so-good fix is to move the script tag to the end of the <body> tag

<body>   ...all content is above the script...    <script src="your-script.js"></script> </body> 
Enter fullscreen mode Exit fullscreen mode

However, this solution is not without its drawbacks. One of the issues is that the browser detects and begins downloading the script only after it has finished downloading the entire HTML document. This can result in noticeable delays, particularly for long HTML documents.

While this delay may go unnoticed by users with fast internet connections, it poses a problem for individuals with slower internet speeds or unreliable mobile connections.

Thankfully, there are two attributes available for the <script> tag that provide solutions to this problem: defer and async.

Async Attribute

The async attribute is ignored if the <script> tag has no src.

<script async src="your-script.js"></script> 
Enter fullscreen mode Exit fullscreen mode

The async attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script downloads “in the background”, and execute once done.

Rendering with Async attribute

Important Considerations When Using the async Attribute

1) The async scripts execute in the load-first order:

It does not guarantee the order of execution of the script. For instance, a smaller script small.js goes second but probably downloads before long.js, so small.js executes first.

<!DOCTYPE html> <html> <head>     <meta charset="UTF-8">     <title>Your Page Title</title>     <script async src="long.js"></script>     <script async src="small.js"></script> </head> <body> <!-- Content of your webpage goes here --> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

2) DOMContentLoaded event and async scripts don’t wait for each other:

When it comes to the order of execution, the DOMContentLoaded event and async scripts are independent of each other. The DOMContentLoaded event may occur before or after an async script, depending on factors such as the script's loading time and whether it is already present in the HTTP cache.

<script>   document.addEventListener('DOMContentLoaded', () => alert("DOM ready!")); </script>  <script async src="your-script.js"></script> 
Enter fullscreen mode Exit fullscreen mode

Defer Attribute

The defer attribute is ignored if the <script> tag has no src.

<script defer src="your-script.js"></script> 
Enter fullscreen mode Exit fullscreen mode

The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, and build DOM. The script loads in the background, and then runs when the DOM is fully built.

Rendering with Defer attribute

Important Considerations When Using the defer Attribute

1) defer guarantees the order of execution of scripts just like regular scripts.

It guarantees the order of execution of the script. For instance, To enhance performance, browsers download scripts in parallel therefore smaller script small.js goes second but probably downloads before long.js, but it still waits and runs after long.js executes..

<!DOCTYPE html> <html> <head>     <meta charset="UTF-8">     <title>Your Page Title</title>     <script defer src="long.js"></script>     <script defer src="small.js"></script> </head> <body> <!-- Content of your webpage goes here --> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

2) DOMContentLoaded event handler waits for the deferred script. It only triggers when the script is downloaded and executed.

<script>   document.addEventListener('DOMContentLoaded', () => alert("DOM ready!")); </script>  <script defer src="your-script.js"></script> 
Enter fullscreen mode Exit fullscreen mode

When should I use what?

1) If the script is modular and does not depend on any other scripts such as independent third-party scripts like counters, and ads then use async.

<!-- Google Analytics is usually added like this --> <script async src="https://google-analytics.com/analytics.js"></script> 
Enter fullscreen mode Exit fullscreen mode

2) If the script relies upon or is relied upon by another script then use defer.

3) If the script is small and is relied upon by an async script then use an inline script with no attributes placed above the async scripts.

Dynamic Scripts

There is another important method of adding a script to a webpage. We can create a script element using JavaScript and add it to the document dynamically. Here's an example:

let script = document.createElement('script'); script.src = "your-script.js"; document.body.append(script); 
Enter fullscreen mode Exit fullscreen mode

Once the script is appended to the document, it starts loading immediately.

It's important to note that dynamic scripts behave as async by default. This means that they will load asynchronously, potentially impacting the order of execution and interaction with other elements on the page.

To make it non-async, we can set

script.async = false 
Enter fullscreen mode Exit fullscreen mode

What if we put both async and defer attributes in the same script tag?

If you specify both, async takes precedence on modern browsers, while older browsers that support defer but not async will fallback to defer.

frontendjavascriptprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.