Table Of Contents
<body> section of the HTML, depending on the specific requirements of the code.
<script> tag, follow this basic syntax:
Let’s see its position within the HTML document.
Placement within HTML
<head> Section: Placing the
<script> tag in the
<head> section is suitable for code that needs to run before the page is fully loaded.
This includes functions that initialize variables, set up configurations, or perform other tasks necessary for the page to render correctly.
<head> <script> // Initialization code </script> </head>
Before the Closing
</body> Tag: Placing the
<script> tag just before the closing
</body> tag is ideal for code that should execute after the HTML content has loaded. This approach helps improve page loading performance.
<body> <!-- HTML content goes here --> <script> // Code that interacts with HTML elements </script> </body>
<html> <head> <title>Your Page</title> <script src="script.js"></script> </head> <body> <h1>Hello, World!</h1> </body> </html>
In another way, you can also put the
<script src='..'> before the closing of the HTML body tag:
<html> <head> <title>Your Page</title> </head> <body> <h1>Hello, World!</h1> <!-- The external js file here --> <script src="script.js"></script> </body> </html>
In the following section, you will learn how to optimize file loading on a web page through the use of the ‘async’ and ‘defer’ attributes.
<script src="script.js" async></script>
Using the async attribute tells the browser to continue parsing the HTML while simultaneously fetching and executing the script.
Let’s move to the ‘defer’ attribute
Another way to optimize page loading is by using the
defer attribute. This attribute ensures that the script is executed only after the HTML has been fully parsed. Example:
<script src="script.js" defer></script>
Unlike async, the defer attribute guarantees the order of script execution and is well-suited for scripts that depend on specific elements in the HTML.
Once you’ve finished your awesome code, let’s execute it through a simple event.
Ensuring Seamless Execution
<script> tags are executed sequentially during the page load. For more precise control, harness event listeners to trigger specific actions when users interact with your webpage.
<script> tag and its placement within HTML, developers gain flexibility in optimizing the execution of their code.
</body> tag enhances page loading performance.
<script src='..'> tag, developers promote code reuse and organization.
The guide also touched upon asynchronous loading and the use of attributes like “async” and “defer” to enhance page performance. Asynchronous loading allows scripts to load simultaneously with other page elements, while the “defer” attribute ensures sequential execution post-HTML parsing, beneficial for scripts dependent on specific elements.