JavaScript Where To
Modern JavaScript: Where and How to Use It
Section titled “Modern JavaScript: Where and How to Use It”JavaScript code can be embedded directly within HTML or linked as external files. Understanding the best ways to include JavaScript is crucial for performance and maintainability.
In HTML, JavaScript code is placed inside <script> tags. You can either write the code directly (inline script) or link to an external JavaScript file.
Inline Script Example (Historically common, but less recommended for larger scripts):
<!-- This script might run before the 'demo' element is loaded, leading to an error. --><script> // Older code might try to access DOM elements here. // document.getElementById("demo").innerHTML = "My First JavaScript";</script>Note: The type="text/javascript" attribute on <script> tags is no longer necessary. JavaScript is the default scripting language in modern HTML. |
|---|
JavaScript Modules and Asynchronous Loading
Section titled “JavaScript Modules and Asynchronous Loading”Modern JavaScript heavily utilizes modules for organizing code. When linking external scripts, the async and defer attributes are essential for optimizing page load performance.
<script src="script.js" defer></script>: The script is downloaded in parallel with HTML parsing and executed after the HTML parser has finished, but before theDOMContentLoadedevent. Scripts withdeferexecute in the order they appear in the document.<script src="script.js" async></script>: The script is downloaded in parallel and executed as soon as it’s available, potentially interrupting HTML parsing. Order of execution is not guaranteed for multipleasyncscripts. Use for independent scripts like analytics.<script type="module" src="main.js"></script>: Loads the script as an ES6 module. Modules are deferred by default.
You will learn more about modules, functions, and events in later chapters.
JavaScript Placement: vs
Section titled “JavaScript Placement: vs ”You can place <script> tags in the <head> or <body> section of an HTML document.
Best Practice: Place scripts at the end of the <body> tag, or in the <head> with defer or async attributes. This prevents script loading/execution from blocking HTML rendering, improving perceived page load speed. |
|---|
Scripts in
Section titled “Scripts in ”Placing scripts in the <head> without async or defer can block page rendering. This is generally discouraged unless the script is small and critical for initial page setup (e.g., polyfills or configuration scripts that must run before the body is parsed).
Scripts in (End of Body - Recommended for non-deferred/async scripts)
Section titled “Scripts in (End of Body - Recommended for non-deferred/async scripts)”Placing scripts just before the closing </body> tag ensures that the HTML structure is loaded before the script attempts to manipulate it. This avoids errors caused by scripts trying to access DOM elements that haven’t been created yet.
Example with script at the end of <body> and modern event handling:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Modern JavaScript Placement</title></head><body> <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <button id="actionButton" type="button">Try it</button>
<script> function changeParagraph() { const demoParagraph = document.getElementById("demo"); if (demoParagraph) { demoParagraph.textContent = "Paragraph changed using modern JavaScript!"; } }
const button = document.getElementById("actionButton"); if (button) { button.addEventListener("click", changeParagraph); } </script></body></html>External JavaScript
Section titled “External JavaScript”For larger applications, it’s best to place JavaScript code in external files (.js extension).
To use an external script, specify the file path in the src attribute of the <script> tag:
<!-- In your HTML file: --><script src="myScript.js" defer></script><!-- Or using type="module" for modern module syntax --><script type="module" src="app.js"></script>External JavaScript files should contain only JavaScript code, not <script> tags.
External scripts behave as if their code was inserted directly at the location of the <script> tag, but async and defer attributes modify this behavior for better performance. |
|---|
Advantages of External JavaScript
Section titled “Advantages of External JavaScript”Using external JavaScript files offers several benefits:
- Separation of Concerns: Keeps HTML structure and JavaScript logic separate, improving code organization.
- Readability and Maintainability: Makes both HTML and JavaScript easier to read, understand, and maintain.
- Caching: Browsers can cache external JavaScript files, speeding up page loads on subsequent visits or across different pages using the same script.
For further learning, explore JavaScript modules (ES6 modules) for better code organization in larger projects.