The async=""
is asynchronous even, ie will not cause rendering locks and one script will not wait for the other, which can be bad if one <script src>
depend on each other <script src>
, however it is preferable to use the async
, as long as you know how to organize, an example I formulated:
Follows the code:
//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");
This way you’ll use the async=""
to avoid rendering blocking and callback will only inject the scripts that depend on jQuery if it has been loaded:
function() {
loadJs("js/bootstrap.js"); //Depende do jQuery
loadJs("js/plugin.js"); //Depende do jQuery
}
Defer and async difference
There is already a great question about respecting the order of statement that can be interesting to read too:
Related: About the boolean attribute Defer and async vs optimization
– rray