No , the use of the async
attribute on <script src="...">
elements is to avoid blocking-rendering .
On the use of Ajax I really do not think it takes so much work, you can just load the script dynamically with document.createElement
, nor even need async
, however it's good to use it, at the end of the answer you have an example of how to load dynamically.
Note that the attribute async
does not has an effect on inline scripts, for example:
<script async>foobar();</script>
When a script tag is requested the page rendering is "locked" at that time until the script is fully downloaded and processed, then only from that point what comes next will be loaded, however many things are unnecessary to wait for the script load, then you can use:
<script src="..." async></script>
What will cause the script to load in parallel / concurrently without crashing rendering, ie you do not need to load the entire script so that the page can render, itself # suggests that you do this for a better "user experience" (UX), I've answered other questions about it, see:
Support
Some older browsers that support async
use async=false
in dynamically added elements did not work as expected
As caniuse
- Firefox 3.6 +
- Internet Explorer 10 +
- Chorme 8 +
- Safari in iOS 5.0 +
- Android 3+ native browser
- Safari 5 on Mac
Multiple JavaScripts with dependencies
Example script to load multiple .js that have dependencies on each other, ie one .js depends on the other being loaded, but still avoid rendering block:
<script>
//Esta função carrega os arquivos javascript
function loadJs(url, callback) {
var js = document.createElement("script");
//Verifica se o callback é uma função
if (typeof callback === "function") {
var isReady = false;
//Executa se for carregado no onload ou readystatechange
function ready() {
if (isReady) return;
//Bloqueia execução repetida do callback
isReady = true;
//Chama o callback
callback();
}
js.onload = ready;
/*Internet explorer (http://stackoverflow.com/q/17978255/1518921)*/
js.onreadystatechange = function() {
if (/^(complete|loaded)$/.test(js.readyState)) ready();
}
}
js.async = true;
js.src = url;
document.body.appendChild(js);
}
loadJs("js/jquery.min.js", function() {
loadJs("js/bootstrap.js"); //Depende do jQuery
loadJs("js/plugin.js"); //Depende do jQuery
});
//Não depende do jQuery
loadJs("js/outros-scripts.js");
</script>