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:
- 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.
- Pausing for Scripts: If a script is encountered, DOM construction halts until the script is fetched and executed.
- 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:
- Scripts in the <head>: These may delay rendering of the
<body>since the browser pauses to load and execute scripts before moving on. - Scripts at the End of <body>: This allows the visual content to load first, providing a better user experience.
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:
-
Place dependent scripts in the correct order. For example, if
scriptB.jsdepends onscriptA.js, importscriptA.jsfirst. -
Use the
deferorasyncattributes to optimize loading:defer: Ensures scripts execute in order after the DOM is fully constructed.async: Loads scripts independently, executing them as soon as they’re ready.
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:
- How to import JavaScript into your HTML files.
- The rendering process and how the DOM is constructed.
- Why script placement matters for performance and interactivity.
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!