async=""
is asynchronous even, that is, it will not cause rendering locks and one script will not wait for the other, which can be bad if a <script src>
depends on the other <script src>
, however it is preferable to use the async
, as long as you know how to organize, an example I formulated:
Follow 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");
In this way you will use async=""
to avoid rendering blocking, and the callback will only inject jQuery-dependent scripts if it has been loaded:
function() {
loadJs("js/bootstrap.js"); //Depende do jQuery
loadJs("js/plugin.js"); //Depende do jQuery
}
Difference of defer and async
There is already a great question about respecting the order of declaration that might be interesting to read as well: