2

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

3

2 Answers 2

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

What about something like script = document.createElement('script');script.async = true;script.src = "url";? This is an external script but it's created dynamically.
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.

1 Comment

How is this loading the script dynamically?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.