How to add javascript

JavaScript can be added to HTML in three ways.


  •  Inline JavaScript
  •  Internal JavaScript
  •  External JavaScript

1.    Inline JavaScript


        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.

Example
<!DOCTYPE html>
<html>
<head>
<title>Inline Js</title>
</head>
</html>
<body>
<button onclick="alert('Button Clicked!')">Click Me</button>
</body>
</html>

Try it yourself

2.    Internal JavaScript


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.


  1. Inside <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.


Example
<!DOCTYPE html>
<html>
<head>
<title>Internal JS</title>
<script>
function sayHello() {
alert('Hello, World!');
}
</script>
</head>
<body>
<button onclick="sayHello()">Click Me</button>
</body>
</html>

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.



Example
<!DOCTYPE html>
<html>
<head>
<title>Internal JS</title>
</head>
<body>
<button onclick="sayHello()">Click Me</button>

<script>
function sayHello() {
alert('Hello, World!');
}
</script>
</body>
</html>

Try it yourself

3. External JavaScript


  • For larger projects or when you want to reuse code across multiple HTML pages, it's best to use an external JavaScript file.
  • This keeps the HTML clean and allows better code organization. The JavaScript file is linked using the <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.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.