HTML Tutorial

HTML Tag: <script>

The <script> tag is used to embed scripts into an HTML document. This allows developers to add dynamic functionality to their webpages.

Usage of <script>:

  1. Source Attribute: Use the src attribute to specify the location of the external script file.
  2. Inline Script: Embed the script directly within the <script> tag using the content between the opening and closing tags.
  3. Deferred and Async Attributes: Use the defer or async attributes to indicate how the script should be loaded. defer loads the script after the page has parsed, while async loads it concurrently.

Attributes of <script>:

Attribute Description
src Location of the external script file
type Specify the script's MIME type (e.g., "text/javascript")
defer Load the script after the page has parsed
async Load the script concurrently
integrity Specify the integrity value to validate the script's authenticity
charset Define the character encoding of the external script file

Examples with <script>:

External Script:

<script src="my_script.js"></script>

Inline Script:

<script>
  // Your JavaScript code here
</script>

Exploring the <script> Tag:

Consider the following HTML example:

<!DOCTYPE html>
<html>
<head>
  <title>My Webpage</title>
  <script src="my_script.js"></script>
</head>
<body>
  <h1>Welcome to my webpage!</h1>
  <button onclick="greetUser()">Greet User</button>
  <script>
    function greetUser() {
      alert("Hello there!");
    }
  </script>
</body>
</html>

In this example:

  • An external script file named "my_script.js" is loaded using the <script src> tag.
  • An inline script defines a function named greetUser().
  • The button with the onclick attribute calls greetUser() when clicked, displaying an alert.

This demonstration showcases the versatility of the <script> tag for enhancing the functionality of webpages.