Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Javascript non blocking

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?


1 Answers

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.

like image 187
T.J. Crowder Avatar answered May 28 '26 08:05

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!