Different ways to load JavaScript in HTML

Photo by Tudor Baciu on Unsplash

Different ways to load JavaScript in HTML

Regular Script Loading Inside of the head tag

  • The browser fetches and executes the script before parsing the HTML body, which means that the script may run before the HTML content has been fully loaded.

  • Manipulating the DOM in the script can lead to errors because the script runs before the DOM is fully constructed, and therefore the DOM may not be available yet.

Regular Script Loading at the end of the tag

  • Once the HTML content has been fully parsed, the script will be fetched and executed.

Async Script Loading

  • The script is fetched asynchronously while the HTML content is being parsed, and it's executed immediately once it has been fully loaded.

Defer Script Loading

  • The script is fetched asynchronously and will not be executed until the HTML content has been fully parsed.