HTML HTML Tutorial HTML Forms HTML Graphics HTML Media HTML APIs HTML Tags



HTML Tag: script

The HTML tag <script> is used to define a client-side script in an HTML document. It is used to embed or reference an executable script within an HTML or XHTML document.

The <script> tag can be used to define JavaScript functions, to include external JavaScript files, and to embed JavaScript code directly into an HTML document. It can also be used to define other scripting languages such as VBScript.

The <script> tag can be placed in the <head> section or the <body> section of an HTML document. When placed in the <head> section, the script is loaded before the page is rendered. When placed in the <body> section, the script is loaded after the page is rendered.

Here are some examples of how the <script> tag can be used:

Example 1: Defining a JavaScript function

The following code defines a JavaScript function that displays an alert message:

<script>
function showMessage() {
  alert("Hello, World!");
}
</script>

To call the function, you can use the following code:

<button onclick="showMessage()">Click me</button>

Example 2: Including an external JavaScript file

The following code includes an external JavaScript file named "script.js":

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

The "script.js" file can contain any valid JavaScript code, such as function definitions, variable declarations, and event handlers.

Example 3: Embedding JavaScript code directly into an HTML document

The following code embeds JavaScript code directly into an HTML document:

<script>
alert("Hello, World!");
</script>

This code displays an alert message when the page is loaded.

The <script> tag is a powerful tool for adding interactivity and dynamic behavior to an HTML document. It allows you to define custom functions, manipulate the DOM, and interact with server-side scripts.

However, it is important to use the <script> tag responsibly and to follow best practices for web development. This includes minimizing the use of inline scripts, using external JavaScript files whenever possible, and ensuring that your code is well-organized and easy to maintain.

References

Activity