Normal (Synchronous) Execution:
async and defer mitigate this by downloading scripts alongside the parser, reducing the overall impact on page load times. Both tags perform similar functions, but they work in somewhat different ways.
The main benefit of async is that it lets you download scripts without interrupting the parser. However, scripts run as soon as they're finished downloading, meaning one script may run before another script even if the latter script was defined first in the page's HTML. This also means scripts could run before the browser has finished building the Document Object Model (DOM). async benefits scripts that don't rely on other scripts or the complete DOM in order to successfully run.
Like async, defer downloads script files alongside the parser. The difference is that defer holds off on executing scripts until after the parser is finished. defer also executes scripts in the order in which they are defined, allowing you to run scripts that depend on other scripts.
defer only works for scripts with a src attribute. However, it guarantees that your scripts will only run after the DOM is complete, and in the order that they appear in the page's HTML.
Tests performed on the Google Maps API showed that using async significantly reduced the time needed to display a map element to the user. With neither attribute enabled, it took 658 milliseconds to fire the DOMContentLoaded event, and 700—1000ms before the user could start customizing the map.
With async enabled, it took only 35ms to fire the DOMContentLoaded event and 300—500ms before the user could start customizing the map. In this test, both async and defer were defined in the script block. Modern browsers default to using async, whereas older browsers that don't support async fall back to defer.
In general, defer offers more benefits over async including preserved execution order, no parser blocking, and access to the page's complete DOM. In addition, defer works reliably when combined with synchronous and async scripts. All modern browsers (with the exception of Opera Mini) support defer as well as async.
Use async if your script...
Use defer if your script...
UnusedCSS helps website owners remove their unused CSS every day. See how much you could save on your website:
You Might Also Be Interested In