External Script File
To optimise code organisation and reusability, it is advisable to store JS code in external files with a `.js` extension. To include an external script file in HTML, use the `<script src=”path/to/file.js”></script>` tag. This approach facilitates code separation, encourages modularity, and enables multiple HTML documents to reuse the same JS file.
While the `<script>` tag can be placed anywhere within the HTML document, it is recommended to include it just before the closing `</body>` tag. By doing so, the HTML content is rendered before loading and executing JS code, improving page load times and ensuring the DOM is ready before script execution.
To prevent JS files from blocking the rendering of the HTML content, you can load them asynchronously. Adding the `async` attribute to the `<script>` tag allows the HTML parser to continue rendering while the JS file loads and executes in the background. This approach is beneficial for non-blocking scripts that do not rely on the order of execution.
Similar to asynchronous loading, the `defer` attribute enables the HTML parser to continue rendering while the JS file is loaded. However, deferred scripts retain the order of execution, ensuring they are executed in the order they appear in the HTML document. Use the `<script defer src=”path/to/file.js”></script>` tag to achieve deferred loading.
External Script Integrity
To enhance the security and integrity of external JS files, you can include an integrity attribute in the `<script>` tag. This attribute, combined with the `crossorigin` attribute, verifies that the file hasn’t been tampered with since its deployment, ensuring the integrity of the script being loaded.
Document Object Model (DOM) Manipulation
Frequently Asked Questions
What is the best way to include JS files in HTML?