1

The question is simple. I have been researching and in similar questions I have not found the answer. Should defer be used in a script loaded at the bottom of the page? Would it be redundant or does it make sense in any situation?

Mr. Mars
  • 762
  • 1
  • 9
  • 39
  • 2
    Multiple scripts at the bottom of the body might benefit from parallel loading. – Teemu Mar 06 '20 at 19:36
  • 1
    Defer at the bottom of body probably doesn't benefit as it's now parsed anyway. I would think defer only makes sense in the head. – Keith Mar 06 '20 at 19:45
  • @Teemu, That is, with multiple scripts would they be downloaded in parallel but executed in order? In this case it is better to put them at the end of the body or on the head so that they are downloaded and available as soon as possible? – Mr. Mars Mar 06 '20 at 20:18
  • 1
    With `defer` the scripts are executed in the order the tags appear in the markup, no matter where the tags are placed. When putting on the head, scripts will get more time to load, that's the correct place to use `defer`. In the Flavio Copes' article Jan has linked, they say it's not useful to add `defer` at the "footer" of the body. Whether this is correct or not, the difference hardly is remarkable. – Teemu Mar 06 '20 at 20:23

2 Answers2

1

I don't think it makes a difference. However, when you defer in <head> the script is fetched async while the HTML is parsing, so it's faster than putting <script> as the last <body> child. A pretty nice overview is provided in Efficiently load JavaScript with defer and async by Flavio Copes.

Jan
  • 133
  • 1
  • 5
1

Browser will parse the document from top to bottom, hence putting the scripts after all the main content will make the parser to reach that <script> later in time; which make the browser to download the script later in time; The delay caused by putting the defer in the bottom is absolutely non-sense, since the browser won't execute them (<script defer>s) before (or during) HTML parser;

Thus it's better to let the browser load ( download ) them (<script defer>) as soon as possible, an have them available to execute as soon as the all the main tasks are done.

Mechanic
  • 5,015
  • 4
  • 15
  • 38