Different Ways to Include External JavaScript in HTML
Tags: javascript, webdev, beginners, programming
Published: 2024-05-26 10:56:52

JavaScript is an essential part of web development, allowing developers to add interactivity and dynamic behavior to web pages. When incorporating external JavaScript files into HTML documents, there are various methods to consider, each with its own pros and cons. In this blog, we'll explore different ways to include external JavaScript in HTML, discuss their advantages and disadvantages, and provide guidance on when to use each method.

## Introduction
JavaScript files can be included in HTML documents using various methods, each affecting page loading and script execution differently. Let's delve into these methods and understand their implications.

## Including External JavaScript in the `<head>`
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="script.js"></script>
</head>
<body>
    <!-- Your HTML content here -->
</body>
</html>
```
**Pros:**
- Ensures scripts are loaded before rendering the page, preventing any JavaScript-dependent errors.
- Guarantees that scripts are available for use as soon as the page starts loading.

**Cons:**
- Can delay the rendering of the page if the script file is large or takes time to load.
- May result in a slower initial page load time.

**When to Use:**
- When JavaScript needs to manipulate the DOM or perform tasks that should occur before the page renders.

**When Not to Use:**
- Avoid if the script file is large or not essential for initial page functionality.

## Before the Closing `</body>` Tag
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- Your HTML content here -->
    <script src="script.js"></script>
</body>
</html>
```
**Pros:**
- Allows the HTML content to load before fetching and executing the script, potentially improving perceived page load speed.
- Scripts won't block other resources from loading.

**Cons:**
- JavaScript execution may be delayed until after the HTML content is rendered, affecting user experience if scripts are essential for initial functionality.

**When to Use:**
- Suitable for scripts that are not critical for initial page functionality or rendering.

**When Not to Use:**
- Avoid for scripts that need to manipulate the DOM or execute before the page renders.

## Using `defer`
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="script.js" defer></script>
</head>
<body>
    <!-- Your HTML content here -->
</body>
</html>
```
**Pros:**
- Executes scripts after the HTML content is parsed, but before `DOMContentLoaded`, ensuring that scripts run in the order they are declared.
- Improves page load time by allowing HTML parsing to continue while the script is downloaded.

**Cons:**
- May still delay script execution if multiple scripts are deferred, as they will execute sequentially.

**When to Use:**
- Ideal for scripts that need to access DOM elements but can safely run after the HTML is parsed.

**When Not to Use:**
- Avoid for scripts that must execute before `DOMContentLoaded` or rely on the immediate availability of DOM elements.

## Using `async`
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="script.js" async></script>
</head>
<body>
    <!-- Your HTML content here -->
</body>
</html>
```
**Pros:**
- Fetches and executes the script asynchronously, allowing HTML parsing to continue without waiting for the script to download.
- Ideal for non-blocking scripts that don't rely on DOM elements or need to execute independently.

**Cons:**
- Scripts may execute out of order, potentially causing dependencies or race conditions.
- Not suitable for scripts that require access to the DOM or must execute in a specific order.

**When to Use:**
- Best for non-essential scripts that can run independently and don't depend on the page's DOM structure.

**When Not to Use:**
- Avoid for scripts that require DOM manipulation or must execute before other scripts for proper functionality.

## Comparison of Methods
| Method                      | Pros                                     | Cons                                                 |
|-----------------------------|------------------------------------------|------------------------------------------------------|
| `<script>` in `<head>`      | - Ensures scripts are available early.   | - May delay initial page load.                       |
|                             | - Prevents JavaScript-dependent errors.  | - May block rendering if script is large.            |
| Before `</body>`            | - Allows HTML content to load first.     | - Delayed script execution.                          |
|                             | - Doesn't block other resource loading.  | - Scripts may not run before DOMContentLoaded.      |
| `defer`                     | - Scripts execute after HTML parsing.     | - Scripts may still block rendering.                 |
|                             | - Improves perceived page load speed.    | - Multiple deferred scripts may execute sequentially.|
| `async`                     | - Fetches and executes script asynchronously. | - Scripts may execute out of order.              |
|                             | - Doesn't block HTML parsing.             | - Not suitable for scripts with dependencies.       |

## When to Use Each Method
- **`<script>` in `<head>`:** Use when scripts are essential for initial page functionality and must be available before rendering.
- **Before `</body>`:** Suitable for non-essential scripts or scripts that don't rely on immediate DOM access.
- **`defer`:** Best for scripts that require access to the DOM but can safely execute after HTML parsing.
- **`async`:** Ideal for non-blocking scripts that can execute independently and don't rely on the page's DOM structure.

## When Not to Use Each Method
- **`<script>` in `<head>`:** Avoid for large scripts or scripts that aren't essential for initial functionality.
- **Before `</body>`:** Not suitable for scripts that need to manipulate the DOM or execute before DOMContentLoaded.
- **`defer`:** Avoid for scripts that must execute before DOMContentLoaded or rely on immediate DOM access.
- **`async`:** Not suitablefor scripts that require access to the DOM or must execute in a specific order.

## Performance Impact
The performance impact of each method depends on factors such as script size, placement, and dependencies. Here's a brief overview:

- **`<script>` in `<head>`:** May delay initial page load if scripts are large or take time to download. However, ensures scripts are available early, potentially reducing script execution delays later.
- **Before `</body>`:** Allows HTML content to load first, improving perceived page load speed. However, scripts may execute after the DOM is fully rendered, delaying script execution.
- **`defer`:** Fetches scripts asynchronously while allowing HTML parsing to continue. Scripts execute after HTML parsing but before `DOMContentLoaded`, improving perceived page load speed.
- **`async`:** Fetches and executes scripts asynchronously, allowing HTML parsing to continue without waiting for the script to download. However, scripts may execute out of order, potentially causing dependencies or race conditions.

## Conclusion
In conclusion, the method you choose to include external JavaScript in HTML depends on various factors, including script dependencies, page load speed, and script execution timing. Each method has its pros and cons, and understanding these factors is crucial for optimizing web page performance and user experience.

- **`<script>` in `<head>`:** Use when scripts are critical for initial page functionality and must be available before rendering.
- **Before `</body>`:** Suitable for non-essential scripts or scripts that don't rely on immediate DOM access.
- **`defer`:** Best for scripts that require access to the DOM but can safely execute after HTML parsing.
- **`async`:** Ideal for non-blocking scripts that can execute independently and don't rely on the page's DOM structure.

By carefully considering these factors and choosing the appropriate method for including external JavaScript, you can optimize your web pages for better performance and user experience.