<script> tags. By placing the script directly within the HTML markup, you can target specific elements and manipulate them dynamically.
To illustrate this method, consider the following example:
In this example, we have an
.js extension. You then reference this file within your HTML document using the
Follow these steps to utilize this method effectively:
- Create a new file and save it with a
- In your HTML document, include the script file using the
Here's an example:
<!DOCTYPE html> <html> <head> <title>My Web Page</title> <script src="script.js"></script> </head> <body> <h1>Welcome to My Web Page</h1> <button onclick="greet()">Click Me</button> </body> </html>
To implement asynchronous loading, you can use the HTML
defer attribute. The
async attribute tells the browser to download the script asynchronously, without delaying the rendering of the rest of the page. On the other hand, the
defer attribute ensures that the script executes after the page finishes parsing.
<!DOCTYPE html> <html> <head> <title>My Web Page</title> <script src="script.js" async></script> </head> <body> <h1>Welcome to My Web Page</h1> <button onclick="greet()">Click Me</button> </body> </html>
Using asynchronous loading techniques can significantly improve your web page's performance and enhance the user experience. However, be cautious when using this method, as it may introduce dependencies and order of execution issues.
- Place Scripts at the End: To optimize page loading speed, it's recommended to place your
<script>tags at the end of the HTML document, just before the closing
</body>tag. This ensures that the content of your web page loads first, allowing for a smoother user experience.
<script src="filename.js"></script> syntax.