A simple and solid approach at deferring javascript execution

In most cases javascript code should be deferred so it doesnt block the page loading process.

Javascript files can be deferred simply like this, the execution order of deferred scripts will be strictly kept by browsers in the order of appearance in the HTML file:

<script defer="defer" src="vendor.js"></script>
<script defer="defer" src="app.js"></script>

However projects might require inline js code. That code will execute before the deferred scripts – which might throw errors if the inline js code depends on libraries loaded via deferred script tags. Inline js code can be deferred like described on stackoverflow:

    window.addEventListener('DOMContentLoaded', function() {
        (function($) {

defer was introduced before async. Its execution starts after parsing is completely finished, but before the DOMContentLoaded event. It guarantees scripts will be executed in the order they appear in the HTML and will not block the parser.


Once all of your js is either triggered by DOMContentLoaded or has the `defer tag it is easy to manage and maintain control of the execution order.