Importing JavaScript

  1. JavaScript in an external file
    1. Many developers prefer to put JavaScript into a separate file and import it
    2. Place only JavaScript in a text file with .js extension
      // myfile.js
      
      function sayHello() {
      	alert("Hello, JavaScript!");
      }
      
      // Call sayHello() as soon as DOM finishes loading
      addEventListener("DOMContentLoaded", sayHello);
      
    3. Import .js file in <script> tag
      <head>
      	<script src="myscript.js"></script>
      </head>
      
    4. Note: You must close the <script> tag and not place any JavaScript inside it
    5. Use multiple <script> tags to import multiple scripts
  2. Load non-blocking JavaScript
    1. <script> tag causes the browser to halt parsing, load the script file, run the code, then resume parsing (see visual)
    2. Blocking occurs because script might write to the page, modify existing elements, or redirect to another URL
    3. defer - Don't run the script until the page has loaded
      <script src="myscript.js" defer></script>
      
      1. Script should not contain document.writeln() statements
      2. Other deferred scripts can be downloaded in parallel
      3. All deferred scripts run in sequence
      4. When to use? If the script relies upon or is relied upon by another script
    4. async - Run the script asynchronously as soon as it is available
      <script src="myscript.js" async></script>
      
      1. Script should not contain document.writeln() statements or modify the DOM immediately
      2. Other async scripts can be downloaded in parallel
      3. No order to when async scripts run
      4. When to use? If the script does not rely on other scripts
  3. Hiding your code
    1. Placing your code in a separate file does not hide it from others
    2. Use an obfuscator to make it difficult for others to read your code
  4. Minimizing
    1. To create a smaller .js file, use a JavaScript minifier like javascript-minifier.com
    2. Minified code is normally saved in a .min.js file