Can we use async attribute to load script asynchronously for script loaded dynamically?
2 Answers
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>
1 Comment
script = document.createElement('script');script.async = true;script.src = "url";? This is an external script but it's created dynamically.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
Add defer or async attribute to dynamically generated script tags via javascript
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.
script loaded dynamically?