Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
JavaScript code can be placed in various locations within an HTML document or in separate external files. Here are common ways to include JavaScript in your web pages:
<script>
tag. This can be placed in the <head>
or <body>
section of your HTML document. <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline JavaScript</title>
<script>
// Your JavaScript code here
function sayHello() {
alert('Hello, World!');
}
</script>
</head>
<body>
<button onclick="sayHello()">Click me</button>
</body>
</html>
.js
extension. This makes the code modular and easier to maintain. Include the external file using the <script>
tag with the src
attribute. index.html: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External JavaScript</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="sayHello()">Click me</button>
</body>
</html>
script.js:
// Your JavaScript code here
function sayHello() {
alert('Hello, World!');
}
async
attribute to load the script asynchronously, which allows the HTML parser to continue parsing the HTML document while the script is being fetched. This is useful for non-blocking script loading. <script src="script.js" async></script>
defer
attribute is used to defer script execution until after the HTML document has been completely parsed. This can be beneficial for maintaining the order of script execution. <script src="script.js" defer></script>
Choose the method that best suits your needs based on the size and structure of your project, as well as your performance considerations.