21

So I've recently learned that putting your js at the bottom of the DOM is antiquated, and that I should be once again putting them in the <head> with the “async” and “defer” attributes.

Great. But I'm a bit confused as to which I should use, based on priority.

So I have:

  • jquery
  • jquery plugins that don't have immediate effects on the look of the page
  • jquery plugins that do have immediate effects on the look of the page
  • my own personal scripts, which have immediate effects on the look of the page, and is also reliant on jquery

Which should get async, and which should get defer?

If I understand all this correctly, the ones that don't have an immediate effect on the look of the site should get defer, while everything else gets async. Correct? Or am I getting these mixed up.

1 Answer 1

26

It's quite simple. You should use [async] for scripts which can be executed in any order, and [defer] for scripts which have to be executed after HTML is parsed.

For example, if you have a script that add social sharing icons next to your posts, and this script doesn't rely on any other script, you can use both [async] and [defer]. But if your scripts requires jQuery, you can't use [async], because if you do, it might turn out that it gets executed before jQuery is loaded and it breaks.

If all your scripts require jQuery, then you shouldn't use [async] at all. As for [defer], it depends on whether your scripts access DOM. For plugins it probably doesn't matter, but you'll probably need it for your own code.

If you wrap your scripts in $(document).ready();, you can use [defer] for scripts which don't have immediate effect (e.g. require user interaction).

Sign up to request clarification or add additional context in comments.

7 Comments

For DOM manipulation script what should i use . defer or async?
@Apoorv You should definitely use [defer]; as for [async], it depends on whether execution order matters to you.
One of the best explanation so far from so many answers. Thanks @MichałPerłakowski
If you place scripts in the head don't you need to use defer in order to allow them to load without blocking the html page loading, irrespecitve of whether they need to access the DOM or not.
According to MDN docs for the script tag using defer prevents the firing of the DOMContentLoaded event. I'm wondering what are the risks of the JS not loading or loading slowly and preventing the initial load of the page?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.