Not, the use of the attribute async
in elements <script src="...">
is to avoid the render lock (blocking-render).
About using Ajax I really do not think it is necessary so much work, can rather load the script dynamically with document.createElement
, it is not even necessary to async
, however it is good to use it, at the end of the answer has an example of how to load dynamically.
Note the attribute async
nay has an effect on inline scripts, for example:
<script async>foobar();</script>
When a script tag is requested to render the page is "locked" at that time until the script is fully downloaded and processed, then only from this point what comes after it will be loaded, however many things are unnecessary to wait for the script to load, then you can use:
<script src="..." async></script>
What will make the script to load parallel/simultaneously without locking the rendering, that is to say, you will not need to load the whole script so that the page can render itself Pagespeed Insights suggests you do this for a better "user experience" (UX), I answered other questions on the subject, see:
Support
In some older browsers that support the async
use async=false
on dynamically added elements did not work as expected
In accordance with kennel
- Firefox 3.6+
- Internet Explorer 10+
- Chorme 8+
- Safari in iOS 5.0+
- Native Android browser 3+
- 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 whether the other is loaded, but still avoid rendering blocking:
<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>
Can you explain better what you mean by "load scripts via ajax"? You directly upload a JS file/code, or is it an HTML tag
<script src="...">
within?– bfavaretto