المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: JavaScript Essential Training, The Complete JavaScript Course 2022 From Zero to Expert


Modern JavaScript loading

Default Behavior

  • (called content / render blocking)
  • Browser stops rendering when JavaScript is encountered. JavaScript is executed before rendering continues. Often referred to as content blocking.
<script src="JS/script.js"></script>

Async

  • Browser downloads JavaScript in parallel while HTML renders. When JavaScript is fully loaded, rendering stops while JavaScript is executed.
  • This is good for some purposes, especially when you need, to get the JavaScript to parse as quickly as possible, and you don’t really care about render blocking.
<script src="JS/script.js" async></script>

Defer

  • Browser downloads JavaScript in parallel while HTML renders, then defers execution of JavaScript until HTML rendering is complete.
<script src="JS/script.js" defer></script>

Regular vs Async vs Defer

END OF BODYASYNC IN HEADDEFER IN HEAD
Scripts are fetched and executed after the HTML is completely parsedScripts are fetched asynchronously and executed immediatelyScripts are fetched asynchronously and executed after the HTML is completely parsed
Use if you need to support old browsersUsually the DOMContentLoaded event waits for all scripts to execute, except for async scripts. So, DOMContentLoaded does not wait for an async scriptDOMContentLoaded event fires after defer script is executed
Scripts not guaranteed to execute in orderScripts are executed in order
Use for 3rd-party scripts where order doesn’t matter (e.g. Google Analytics)This is overall the best solution! Use for your own scripts, and when order matters (e.g. including a library)

Note: You can, of course, use different strategies for different scripts. Usually a complete web applications includes more than just one script.

Summary

In a nutshell:

  • async/defer Should Be Standard.
  • Only use render blocking when you have a specific reason.
  • Loading JavaScript in the footer is now an anti-pattern.
  • Never load JavaScript in the head.