How does Javascript’s async attributo work?

Asked

Viewed 127 times

3

I was reading about the attribute async, which is used in the tag <script>, and I got curious and doubtful about some things.

According to the W3school:

A script that will be run asynchronously as soon as it is available

Translating:

A script that will run asynchronously, so it is available

I have a few questions regarding this implementation:

  1. With the implementation of the async, I must now stop put some scripts in <body> from my page (as in the case of jQuery UI, which is heavy), or are things different ?

  2. Using it may imply some performance problem or variable definitions in a certain context (e.g., if I use in the jQuery, occur some "excessive waiting" to define the variable $ as a reference to jQuery)?

  3. The assync does the same (or at least does the same) as definition of a callback in window.onload?

  4. What are the main advantages of using it ?

  • Briefly, the script is downloaded without blocking the page rendering. It then runs, even if the page has not been fully loaded. Maybe that question help on some points.

  • I marked as duplicate because I believe that the answer to the other question clarifies all these doubts.

  • All right @bfavaretto

1 answer

2


  1. I believe what should matter with the attribute async is the use of DOM manipulation by Javascript, which may end up creating more problems if the elements are not loaded when the script needs them.

  2. Yes. If you’re going to use one $("input") but the input is generated after the function reaches that point, you will have problems.

  3. No, the async executes the code at the moment it is completely downloaded by the browser.

  4. The main advantage would be for mobile users, with faster Javascript execution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.