The <script> and <noscript> Tags
The <script>
tag is used to embed scripts, typically JavaScript, into a web page. The <noscript>
tag specifies content to be displayed when a browser doesn’t support scripting or has it disabled.
Using <script>
The <script>
tag is primarily used to load JavaScript code:
1 | <script> |
This code will execute immediately when embedded in a webpage.
Loading External Scripts:
You can also use <script>
to load external script files by providing the URL in the src
attribute:
1 | <script src="javascript.js"></script> |
This will load and execute the javascript.js
file.
Script Type:
The type
attribute specifies the script type. For JavaScript, it’s optional as it’s the default:
1 | <script type="text/javascript" src="javascript.js"></script> |
For ES6 modules, use:
1 | <script type="module" src="main.js"></script> |
For browsers that don’t support ES6 modules, you can use the nomodule
attribute as a fallback:
1 | <script type="module" src="main.js"></script> |
Other Important Attributes:
async
: Specifies that the script should be executed asynchronously.defer
: Indicates that the script should be executed after the page has finished parsing.crossorigin
: Configures the script to be loaded using CORS.integrity
: Provides a hash of the script to prevent tampering.nonce
: A cryptographic nonce used in Content Security Policy.referrerpolicy
: Specifies how to handle theReferer
HTTP header.
Using
The <noscript>
tag is used to provide alternative content when JavaScript is not available or disabled:
1 | <noscript> |
This content will only be shown if the browser can’t execute JavaScript. Users might disable JavaScript to save bandwidth, extend battery life on mobile devices, or protect their privacy by preventing tracking.
Link to original article: