Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use defer on script which are already at just before the bottom body tag?

This question has always bothered me every time I put my js files at the bottom of the page. if I put all js files at the bottom before the closing body tag then I think that the browser will first download all the html and style sheets then it will parse the html and css and at last it will send requests for js files. So,

  • Would using defer on js files which are already at the bottom make any difference?
  • Are non deferred scripts at the end just before body tag render blocking?

Another question I have is if I put all js file in the head and use defer on them. Would this be equivalent to placing all js files at the bottom? Would seeing js with defer in head the browser make request to the server and then continue downloading rest of html file or will it make request to server only after downloading all html and css?

As far as I know async is equivalent to defer and the only difference is the js will be executed when downloaded without respecting the order of files. So,

  • Would using async on js files which are already at the bottom make any difference except from the order in which they are executed?
like image 857
user31782 Avatar asked Nov 05 '16 13:11

user31782


2 Answers

Looking through the HTML 5.2 spec for Scripting, one finds this illustration W3C uses.

What we see here is that using defer fetches the script while the HTML is being parsed, but waits until parsing is concluded before executing.

async, on the other hand, fetches alongside parsing, and once the fetch is complete, HTML rendering is paused to execute the script.

Since HTML execution is synchronous, one can assume that using defer on scripts placed just before </head> would be almost like placing them just before </body>.

However, as Chris Moschini states, I would not trust defer. I feel this StackOverflow answer as a whole would better explain how defer affects loading JavaScripts.

like image 55
Nathanael McDaniel Avatar answered Oct 27 '22 05:10

Nathanael McDaniel


The defer attribute is a boolean attribute.

When present, it specifies that the script is executed when the page has finished parsing.

Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

like image 42
shamim khan Avatar answered Oct 27 '22 06:10

shamim khan