HTML5 script async attribute can be used to load a script asynchronously. with async one can also use onload attribute to attach any javascript code which gets executed once script is fetched and executed.
Code used in this tutorial (file: async_sync_demo.js
)
document.querySelector("pre").innerText += "In async_sync_demo.js\n";
Example – script tag without async
<pre></pre> <script src="/demo2/async_sync_demo.js"></script> <script> document.querySelector("pre").innerText += "Outside async_sync_demo.js\n"; </script>
Example – script tag with async and onload
<pre></pre> <script src="/demo2/async_sync_demo.js" async onload="onload_handler()"></script> <script> document.querySelector("pre").innerText += "Outside async_sync_demo.js\n"; function onload_handler() { document.querySelector("pre").innerText += "Loaded async_sync_demo.js\n"; } </script>
Specification and Browser compatibility
Specification | Status | Categories |
---|---|---|
async attribute for external scripts | WHATWG Living Standard | DOM, HTML5 |
Chrome | Firefox | IE | Edge | Safari | Opera |
---|---|---|---|---|---|
Yes 8+ | Yes 3.6+ | Yes 10+ | Yes 12+ | Yes 5.1+ | Yes 15+ |
Android Chrome | Android Firefox | iOS Safari | IE Mobile | Opera Mobile |
---|---|---|---|---|
Yes 47+ | Yes 44+ | Yes 5.0-5.1+ | Yes 10+ | Yes 33+ |
source: caniuse.com