DEV Community

Abhinav Singh
Abhinav Singh

Posted on

Different Ways to Include External JavaScript in HTML

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>

<!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>
Enter fullscreen mode Exit fullscreen mode

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

<!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>
Enter fullscreen mode Exit fullscreen mode

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

<!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>
Enter fullscreen mode Exit fullscreen mode

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

<!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>
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (3)

Collapse
 
oculus42 profile image
Samuel Rouse

I like the structuring of this article. It provides a clear path to follow and understand the information presented!

The point about DOM manipulation is counter to my understanding and experience.

A script placed in the head without special attributes executes before the DOM is loaded and rendered. Unless some logic delays code execution until after domContentLoaded, a script in the head may not see/have access to the DOM.

Scripts are, or at least were, placed at the end of the body for this express purpose; they load after the DOM is parsed to have access to the DOM for manipulation. defer provides similar results for DOM access as scripts at the end of the body.

I unfortunately wasn't able to quickly locate more definitive sources than StackOverflow, but I would be interested to understand more about this distinction if have links to share on the topic.

Collapse
 
efpage profile image
Eckehard

You did not mention scripts that are directly included in the HTML-page. If you include an external script via scr="", this needs to be fetched before execution. So, an HTTP-request needs to be sent to the server, which often takes much more time than the script execution. Putting script text into the page can be significatly faster, so you do not get any delay using inline scripts.

Collapse
 
explorykod profile image
Amaury Franssen

Great article to clarify choices, very useful especially when you have no access to a particular framework.