Importing Scripts into HTML

How to Import JavaScript into HTML

JavaScript enables interactivity in web pages. Importing JavaScript into your HTML file is straightforward:

Basic Syntax

<!DOCTYPE html>
<html>
    <head>
        <title>Importing JavaScript</title>
        <script src="your-script.js"></script>
    </head>
    <body>
        ...
    </body>
</html>

You can specify either relative or absolute paths in the src attribute:

Example with External Library

<script src="https://code.jquery.com/jquery-3.6.0.js" 
        integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" 
        crossorigin="anonymous"></script>

Learn more about the <script> tag on MDN.

How the Browser Renders HTML, CSS, and JavaScript

The rendering engine of a browser is responsible for displaying content. Here’s an analogy to help you understand:

Rendering Engine as a Factory: Imagine a factory receiving raw materials (HTML, CSS, JavaScript). These materials are processed in specific steps to create a final product (your webpage).

Steps in Rendering:

  1. Constructing the DOM: The HTML is parsed into a tree structure called the DOM (Document Object Model). Think of this as the blueprint for your webpage.
  2. Pausing for Scripts: If a script is encountered, DOM construction halts until the script is fetched and executed.
  3. Rendering the Page: The DOM combines with CSS and JavaScript to produce the visual webpage.

Script Placement

The placement of <script> tags affects the rendering process:

Example:

<!DOCTYPE html>
<html>
    <head>
        ...
    </head>
    <body>
        ...
        <script src="your-script.js"></script>
    </body>
</html>

Real-World Analogy: Placing your scripts at the end of <body> is like finishing the construction of a house before decorating it. The house is functional (visible to users) while you add enhancements (scripts).

Best Practices for Script Placement

Here are some best practices:

Example with defer:

<script src="your-script.js" defer></script>

Real-World Example: When loading analytics or third-party tracking scripts, use async to ensure they don’t block the main content.

Conclusion

In this tutorial, you learned:

Understanding these concepts is crucial for building efficient and interactive web applications. Experiment with script placement and observe how it affects rendering in your projects!