Different Ways of Adding JavaScript to a Page

  1. Inline JavaScript
  2. External JavaScript

Inline JavaScript

  • In HTML, JavaScript code is inserted between <script> and </script> tags.
  • Scripts can be placed in the <body> or <head> (or both) section of an HTML page.

External / Imported JavaScript

  • Import external JS file using src
  • You can place an external script reference in <head> or <body> or both as you like.

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

Importing script properly

  • Inline JS
  • External JS at the end of BODY tag
  • External JS in HEAD section
  • External JS with async keyword
  • External JS with defer keyword
<html>
<body>
    <!-- Inline JS -->
    <script type="text/javascript">
      document.write("Welcome")   
    </script>
  
  <!-- External JS -->
  <script src="app1.js"></script>
  <script src="app1.js"></script>
</body>
</html>

Inline JS

  • Executed directly when the browser (HTML parser) reaches this tag, blocks HTML parsing & rendering.
  • Typically only used for very trivial/small sites/scripts. Or you’d create a huge HTML file otherwise

External JS

  • Requested & loaded when browser (HTML parser) reaches this tag.
  • Execution behavior depends on configuration: async and defer allows HTML parser to continue
  • In Head section
    • Immediatley loaded & executed, blocks HTML parsing & rendering
    • Parse HTML + Load Script + Exe Script + Parse HTML
  • End of Body
    • Parse HTML + Load Script + Exe Script
  • async
    • Start loading JS as soon as possible without blocking HTML parsing.
    • Execute JS immediately after loading JS is done by blockig HTML parsing.
  • defer
    • Start loading JS as soon as possible without blocking HTML parsing.
    • Execute JS only after HTML parsing is done.
    Page: /