How to Include JavaScript in HTML
Discover the three ways to add JavaScript to your HTML and learn the professional best practices for creating fast, maintainable websites.
Hello, HTML!
<h1>Hello, HTML!</h1>
Internal JavaScript: The <script> Tag
You can embed JavaScript code directly within your HTML file using the <script>
tag. Any code placed between the opening <script>
and closing </script>
tags is executed by the browser as it parses the page. This is great for small, page-specific scripts.
External JavaScript: Linking a .js File
For more complex logic, it's best to keep your JavaScript in a separate .js
file. You link this file using the <script>
tag with the src
(source) attribute. This improves organization, makes the code reusable, and allows the browser to cache the file for faster loading.
Inline JavaScript: Event Attributes
Inline JavaScript is code placed directly inside an HTML attribute, like onclick
. For example: <button onclick="alert('Hello!')">Click Me</button>
. While quick for simple tasks, this method is generally discouraged as it mixes structure (HTML) with behavior (JS), making the code harder to maintain.
Placement Matters: Head vs. Body
The placement of your <script>
tags matters. Placing them in the <head>
can block the rendering of your page while the script is being downloaded and executed. The common best practice is to place scripts just before the closing </body>
tag. This ensures all HTML content is parsed and visible before any scripts run, improving the user experience.
Practice Zone
Interactive Test 1: Sort the Scripts
Drag the code snippets to the correct method: Internal or External.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Link the File
Complete the `script` tag to link an external file named `main.js`.
Rellena los huecos en cada casilla.
<script =""></script>
Practice Example: Code Editor
Write a complete HTML document that uses an internal script to change the content of the `p` tag to "This text was added with JavaScript!".
JavaScript Best Practices
Knowing *how* to include JavaScript is the first step. Knowing *how to do it well* is what makes you a great developer. Here are some professional best practices.
1. Prioritize External Files
For any script longer than two or three lines, use an external .js
file. This separates concerns, makes your code much easier to read and maintain, and allows browsers to cache the script, speeding up subsequent page loads.
2. Understand `async` and `defer`
When linking an external script, you can add attributes to control how it loads. These are powerful tools for optimization.
- `defer`: The browser downloads the script *while* it continues parsing the HTML, and only executes it *after* the HTML parsing is complete. This is often the best choice.
- `async`: The browser downloads the script and executes it as soon as it's available, which could be *before* the HTML is fully parsed. This can block rendering and should be used for independent scripts, like analytics.
<script src="app.js" defer></script>
3. Avoid Inline JavaScript
Placing JS in `onclick` attributes is hard to debug and maintain. Instead, use JavaScript's `addEventListener` to attach functionality to elements from your external script file. This is a core principle of "unobtrusive JavaScript".
// Bad: Inline JS
<button onclick="handle_click()">
// Good: Unobtrusive JS
document.querySelector('button')
.addEventListener('click', handle_click);
Practical Takeaway: Link external JS files using `defer` and place them before the closing `</body>` tag. Use `addEventListener` instead of inline event handlers. This setup provides the best balance of performance and maintainability.
JavaScript Integration Glossary
- <script>
- The fundamental HTML tag used to either contain JavaScript code directly (internal) or link to an external JavaScript file.
- `src` attribute
- The "source" attribute for the
<script>
tag. Its value is the URL or path to an external.js
file. - `defer` attribute
- A boolean attribute that tells the browser to execute the script only after the document has been fully parsed. It does not block rendering.
- `async` attribute
- A boolean attribute that allows the script to be downloaded and executed asynchronously, without blocking page rendering. Execution can happen at any time.
- Inline JavaScript
- JavaScript code written directly inside an HTML attribute, such as `onclick` or `onmouseover`. Generally avoided for modern development.
- DOM (Document Object Model)
- The tree-like structure of HTML elements that the browser creates. JavaScript's primary function on a webpage is to interact with and manipulate the DOM.