Embedding JavaScript
A webpage is just static text until JavaScript breathes life into it. But how does the browser know where your JS logic is? Let's explore the three ways to embed JavaScript into HTML.
Inline JavaScript (The Anti-Pattern)
You can execute JS directly inside HTML tags using event attributes like onclick or onmouseover. While easy for a tiny test, this violates the principle of separation of concerns. It makes your HTML messy and your JS impossible to reuse. Avoid this in production.
Internal JavaScript
By using the <script> tag without a source, you can write JS directly inside your HTML file. This is acceptable for small scripts, but it still means your JS can't be cached by the browser independently of the HTML page.
External JavaScript & Performance
The gold standard. Use <script src="file.js"></script>. This separates logic from markup, keeps code clean, and allows browsers to cache the file.
The Async vs Defer Dilemma
When a browser sees a script in the <head>, it stops building the DOM to download and execute it. To fix this, we use attributes:
- defer: Downloads the script in the background, but waits to execute it until the HTML parsing is completely finished. Ensures execution order.
- async: Downloads in the background and executes the moment it's ready, pausing HTML parsing briefly. Execution order is not guaranteed.
View Full Transcript+
This section contains the full detailed transcript of the video lessons regarding how the browser encounters the script tag, the historical reasons we put scripts at the bottom of the body tag, and how modern HTML5 attributes like defer and async have changed the best practices for performance optimization.
