Attribute | Specification |
---|---|
src | Specifies the path to a JavaScript file, either relative or absolute. |
type | Defines the MIME type; mandatory in HTML4, optional in HTML5. |
async | Executes the script asynchronously (for external scripts); no value required except in XHTML. |
defer | Executes the script after page parsing is complete (for external scripts); no value required except in XHTML. |
charset | Specifies the character encoding in an external script file, e.g., UTF-8. |
crossorigin | Determines how the element handles crossorigin requests. |
nonce | Utilized in Content Security Policy checks (CSP3). |
Dealing with Disabled JavaScript
In scenarios where client browsers lack JavaScript support or have it disabled, potentially due to security concerns, informing users about script execution can be achieved using the <noscript> tag. The <noscript> content displays when JavaScript is disabled.
<script> document.write(“Hello, world!”); </script> <noscript>This browser does not support JavaScript.</noscript>
Linking to an External JavaScript File
The src attribute functions akin to href for anchors, accepting absolute or relative URLs. Typically placed within the <head> tags at the document’s beginning.
<script src=”JSfile.js”></script>
Direct Inclusion of JavaScript Code
Alternatively, instead of linking to an external file, JavaScript code can be directly embedded in HTML.
<script> //JS code </script>
Including a JavaScript File for Asynchronous Execution
<script type="text/javascript" src="URL" async></script>