Similar to internal scripts, you can place the <script> element for external scripts in the <head> or <body> sections of your HTML document. However, using the “defer” or “async” attributes can help improve page loading performance:
- defer: When using the “defer” attribute, the browser downloads the external script file while parsing the HTML but executes the script only after the HTML has been fully parsed.
- async: The “async” attribute allows the browser to download and execute the script file asynchronously, without pausing the HTML parsing.
<script src="your-script.js" defer></script> <script src="your-script.js" async></script>
Placement Best Practices
While the placement of the <script> element depends on your specific requirements, some best practices can help you ensure optimal performance:
- When using multiple <script> elements, be mindful of the order in which they are placed. If one script depends on another, ensure that the dependent script is placed after the script it relies on.