Shopware: async vs defer – use defer

We build a payment plugin and currently working on the release on the Shopware store. One of the feedback we got is to either add async or defer to the externally loaded <script>

The difference between the two is simple once it is understood but before that it sounds the same – and it is not at all and breaks your page if you do it wrong – be there, done that (thankfully while testing).

Both (defer and async) tell the browser to load the script non-blocking, so the browser will continue loading the document and parse the DOM to render everything. But the big difference is:

  • For module scripts, if the async attribute is present then the scripts and all their dependencies will be fetched in parallel to parsing and evaluated as soon as they are available.
  • Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.

TL;DR both make scripts load in parallel to the DOM, but defer makes the DOMContentLoaded event to wait until the script is loaded and executed! That means for the context of Shopware, that our Shopware.PluginManager is waiting for the scripts.

If we use async, the Shopware.Plugin might execute before the script is loaded and end in "YourExternalVariable" is undefined errors.

Leave a Reply

Discover more from Winkelwagen

Subscribe now to keep reading and get access to the full archive.

Continue reading