JavaScript Placement

JavaScript can be placed in HTML in a few different ways. Here are three common methods:

Inline Scripting: JavaScript code can be placed directly in the HTML document using the <script> tag. The script tag can be placed in the head or body of the HTML document.

Example:

<!DOCTYPE html> 
<html>
 <head> <title>Example</title> <script> // JavaScript code goes here
 console.log("Hello, world!"); </script> 
</head> <body> <h1>Hello, world!</h1> </body> </html>

External Script File: JavaScript code can also be placed in an external file and then linked to the HTML document using the <script> tag. This method is often preferred because it allows for better organization and separation of concerns.

Example:

<!DOCTYPE html> 
<html> 
<head> <title>Example</title> <script src="script.js"></script> 
</head>
 <body> <h1>Hello, world!</h1>
 </body> 
</html>

In this example, the JavaScript code is stored in a separate file called "script.js" and linked to the HTML document using the src attribute.

Asynchronous Script Loading: You can also load JavaScript code asynchronously using the async attribute in the <script> tag. This allows the HTML document to continue loading while the JavaScript code is downloaded and executed.

Example:

<!DOCTYPE html> 
<html> 
<head> <title>Example</title> <script async src="script.js"></script> 
</head>
 <body> <h1>Hello, world!</h1> </body> 
</html>

In this example, the async attribute is added to the <script> tag to indicate that the JavaScript code should be loaded asynchronously.

Last updated