JS Basic Tutorial
JavaScript can be added to HTML in three ways.
You can place JavaScript directly inside HTML elements using the onclick
, onmouseover
, or similar event attributes.
Warning
This method is not recommended for larger projects due to its limited flexibility and maintainability.
Try it yourself
You can add JavaScript directly in the <head>
or <body>
section of your HTML document using the <script>
tag. This keeps your JavaScript within the same HTML file.
<head>
: Adding JavaScript inside the <head>
runs the script before the page is fully loaded. This is useful for small scripts but can slow down page rendering if the script takes too long to load.
Try it yourself
2. Inside <body>
:
If you put your JavaScript at the end of the <body>
section, it ensures that the entire page content has loaded before the script runs, which is a better practice for performance.
Try it yourself
<script>
tag, but the actual code is stored in a separate .js
file.Best Practices
Place scripts at the bottom of <body> or use the defer attribute in the <head> to prevent blocking the rendering of the page.
Use external JavaScript for code separation and better maintainability.
Avoid inline JavaScript as it mixes content (HTML) with behavior (JavaScript), making the code harder to maintain.