Вопрос

What are the different methods(comparison in terms of efficiency) in rendering Javascript in a non-blocking manner?. I've heard about the defer attribute that can be used with the script tag. Are there other such methods and if there are then what are their advantages over defer?

Это было полезно?

Решение

I've heard about the defer attribute that can be used with the script tag.

Yes, defer and async make the script (possibly) not run synchronously during the initial parsing/rendering.

Are there other such methods...

Yes, if you create a script element in JavaScript and append it to the DOM, that doesn't hold up the page parsing/rendering either. E.g.:

<script>
(function() {
    var script = document.createElement('script');
    script.src = "/path/to/your/async/script.js";
    document.getElementsByTagName('script')[0].parentNode.appendChild(script);
})();
</script>

...and if there are then what are their advantages over defer?

defer and async aren't universally supported and some browsers have some quirks around them. In particular, IE < 9 may execute defer'd scripts out of order, whereas defer'd scripts are meant to be processed in order (just not during the parsing/rendering of the page). If you add the script elements yourself, you can hook their load event and then load the next script (or use something like RequireJS which does that -- and so much more -- for you). Other than that, not much.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top