DEV Community

Discussion on: Do you need async and/or defer?

Collapse
 
michaelcurrin profile image
Michael Currin

Thanks for sharing.

You've covered how both work but let me add a suggestion when async is a good idea.

Async could load before the DOM had even started or way after it is complete. So it must not rely on something in the DOM (defer would be good in that case)

As you said, async tags don't follow an order so an async tag must not rely on another script or have another script rely on it. (Defer follows order as you said so works with dependence).

So it is independent of the DOM (what the user sees) and other tags, that means it must be used for something like Google Analytics. So your tracking doesn't block a user from viewing the page.

Another case is if you depend on something in the DOM but you fire the function at intervals or on an event.

I got both of those ideas from this article.

medium.com/javascript-in-plain-eng...

Async looks really specialized so I can see why you don't use it.

And defer is a good choice for something that interacts with the DOM but is not essential to the page looking presentable. Like a chatbot tab or image gallery.