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
2
3
<script>
console.log('hello world');
</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
2
<script type="module" src="main.js"></script>
<script nomodule src="fallback.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 the Referer HTTP header.

Using

The <noscript> tag is used to provide alternative content when JavaScript is not available or disabled:

1
2
3
<noscript>
Your browser cannot execute JavaScript. The page may not display correctly.
</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:

https://wangdoc.com/html/script