2

Can we use async attribute to load script asynchronously for script loaded dynamically?

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
  • Can you elaborate a bit more on what you mean by `script loaded dynamically`? – Dinesh Pandiyan Nov 24 '18 at 06:08
  • Yes.Will “Async” attribute loads script asynchronously when used for a script that is dynamically added to the DOM – user3190467 Nov 24 '18 at 06:11
  • Possible duplicate of [Is the "async" attribute/property useful if a script is dynamically added to the DOM?](https://stackoverflow.com/questions/3408805/is-the-async-attribute-property-useful-if-a-script-is-dynamically-added-to-the) – Dinesh Pandiyan Nov 24 '18 at 06:19

2 Answers2

1

By script loaded dynamically, if you mean adding javascript code dynamically to your page, then the answer is No.

async attribute can only be used on loading external scripts that are referred to via a URL specified in src attribute.

The async attribute is only for external scripts (and should only be used if the src attribute is present)

Example, You can load only scripts like this asyncronously

 <script src="external-file.js" async></script> 
Dinesh Pandiyan
  • 5,814
  • 2
  • 30
  • 49
  • What about something like `script = document.createElement('script');script.async = true;script.src = "url";`? This is an external script but it's created dynamically. – Barmar Jun 15 '23 at 19:40
1

It is an interesting point.

Here is an example, some Similar StackOverflow questions, and jQuery Document link For use of Async attribute

Example:

<!DOCTYPE html>
<html>

<head>
    <title>Async Test Attribute</title>
</head>

<body>
    <script src="async_demo.js" async></script>
    <h2>Welcome to Demo!</h2>
    <script>
        console.log('HELLO NON-async');
    </script>
</body>

</html>

async_demo.js

console.log('HELLO Async');

Screencast for above code: https://hareen-nipl.tinytake.com/sf/MzEwNzYzOV85MzEzNTgz

Async jQuery : http://forum.jquery.com/topic/jquery-ajax-async-vs-html5-script-async

W3School Document: https://www.w3schools.com/tags/att_script_async.asp

Similar StackOverflow questions

  1. Add defer or async attribute to dynamically generated script tags via javascript

  2. Is the "async" attribute/property useful if a script is dynamically added to the DOM?

Please comment down below if you have any questions for the same.