Search code examples
javascriptdeferred-loading

Should defer be used in scripts that are loaded just before the body closing tag?


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?


Solution

  • 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.