does javascript load before html

Welcome to Techminati

Be apart of our great community, join today!

G

gukesh

No, JavaScript does not load before HTML by default. Here's how it typically works:

  • HTML is loaded and parsed by the browser first.
  • As the browser encounters JavaScript code (through <script> tags), it halts the parsing of HTML, loads the script, and then resumes rendering the HTML.

How to Control Script Loading:​

  • Default Behavior: If you place a <script> tag in the <head>, the script is loaded and executed before the rest of the HTML is fully parsed, which can block rendering.
  • To Avoid Blocking:
    1. Defer Attribute:
      • <script src="script.js" defer></script>
      • This tells the browser to load the script in parallel with the HTML but execute it after the entire HTML is fully parsed.
    2. Async Attribute:
      • <script src="script.js" async></script>
      • This loads the script asynchronously (without blocking HTML parsing), but it can execute as soon as it’s ready, even before the full HTML is parsed.
  • Placing Scripts at the End of the Body:
    • If you put your <script> tags just before the closing </body> tag, the HTML is parsed first, and then the script is executed.
 
Back
Top Bottom