HTML5 script async – how to load script asynchronously

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>
refresh

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>
refresh

Specification and Browser compatibility

SpecificationStatusCategories
async attribute for external scriptsWHATWG Living StandardDOM, HTML5
Desktop
ChromeFirefoxIEEdgeSafariOpera
Yes 8+ Yes 3.6+ Yes 10+ Yes 12+ Yes 5.1+ Yes 15+
Mobile
Android ChromeAndroid FirefoxiOS SafariIE MobileOpera Mobile
Yes 47+ Yes 44+ Yes 5.0-5.1+ Yes 10+ Yes 33+
source: caniuse.com
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments