javascript where to
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:
- Inline JavaScript: You can include JavaScript directly within your HTML file using the
<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>
- External JavaScript File: For larger projects, it’s common to place JavaScript code in external files with a
.js
extension. This makes the code modular and easier to maintain. Include the external file using the<script>
tag with thesrc
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!');
}
- Asynchronous Script Loading: You can use the
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: The
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.