Different ways to load JavaScript in HTML

Table of contents

No heading

No headings in the article.

Regular Script Loading Inside of the head tag

  • Browser fetches and executes the script first before parsing the HTML body.

  • An error might occur here when you're manipulating the DOM because script is executed first and DOM doesn't exist yet.

f8f92c36-6a15-4888-bdb3-1ce0ca58b88f.png

Regular Script Loading at the end of the tag

  • The Script will be fetched and executed when the HTML is parsed completely.

d2248a60-77b8-462f-bacc-19bae7a242dd.png

Async Script Loading

  • Fetches the script asynchronously while the HTML is being parsed and immediately executes it when the script has been loaded completely.

74cc7299-2f21-4ba2-8032-b95ff9eafb28.png

Defer Script Loading

  • The script is being fetched asynchronously and will only be executed when the HTML is parsed completely.

79904536-69e7-4c2e-833c-9d03113ec546.png