JavaScript can be added to a web page in several ways:
-
Inline Script:
JavaScript code can be directly included within HTML elements using the
onclick, onload,or other event attributes. For instance:<button onclick="myFunction()">Click me</button> <script> function myFunction() { alert("Hello, World!"); } </script> -
Internal Script:
JavaScript can be placed within the <script> tag in the HTML document, usually in the <head> or <body> section. This method allows writing scripts directly in the HTML file.
<script> function myFunction() { alert("Hello, World!"); } </script> -
External File:
JavaScript code can be placed in an external file with a .js extension and included in HTML using the <script> tag with the src attribute pointing to the file path.
HTML file:
<script src="script.js"></script>JavaScript file (
script.js):function myFunction() { alert("Hello, World!"); } -
Asynchronous Loading:
Using the
asyncattribute in the script tag allows the browser to download the script asynchronously while parsing the HTML. This can enhance page loading performance by not blocking other processes.<script src="script.js" async></script> -
Dynamic Script Insertion:
JavaScript can create and append script elements dynamically to the DOM, allowing for loading scripts based on certain conditions or events.
const script = document.createElement('script'); script.src = 'script.js'; document.body.appendChild(script); -
Defer Loading:
The
deferattribute in the script tag delays script execution until the HTML parsing is complete. Multiple deferred scripts are executed in the order they appear in the document.<script src="script.js" defer></script>
Each method has its advantages and use cases, depending on factors such as script size, performance requirements, and the need for modularity in the codebase.