HTML script src
Created By: chatGPT
HTML allows you to include external scripts such as JavaScript by using the
<script>
tag with the src
attribute. This is useful for keeping your code organized and modular. Here’s how you can do it: <head>
<script src="path/to/your/script.js"></script>
</head>
When the browser encounters the
<script>
tag, it will fetch and execute the JavaScript file specified in the src
attribute. Here are some important points to remember: // Example of an external JavaScript file (script.js)
console.log('Hello, World!');
Placement of the
<script>
tag is crucial. If your script interacts with the DOM, consider placing the tag just before the closing </body>
tag to ensure that the HTML is fully loaded before the script executes. Here’s the alternative placement: <body>
<h1>Hello, World!</h1>
<script src="path/to/your/script.js"></script>
</body>
Additionally, if your script relies on the DOM being completely loaded, you can use the
defer
or async
attribute with the <script>
tag. The defer
attribute ensures that the script is executed in the order it appears, while async
allows the script to be executed as soon as it’s loaded: <head>
<script src="path/to/your/script.js" defer></script>
</head>
To summarize, using the
src
attribute in the <script>
tag helps you load external JavaScript files efficiently, keeping your HTML clean and maintainable. // Clean separation of concerns with external scripts
<head>
<script src="path/to/script.js" async></script>
</head>