Home » HTML » HTML Script

HTML Script

The <script> tag is used to add client-side scripts, like javascript in the document. It can be defined anywhere within the webpage. The <script> element either contains scripting statements, or it points to an external script file through the src attribute.

Syntax:

<script> code to be executed.. </script>

JavaScript Attributes

Attributes Description
src It specifies the URL of an external script file.
type It specifies the type of the script.
async It specifies that the script will be executed asynchronously with the webpage. It should only be used with external scripts.
defer It is a boolean value which specify that the script is executed after document has been parsed completely.
Note : The type attribute was required in HTML 4 but it is optional in HTML 5. There is no need to define the type of the script in HTML 5.

Uses of HTML script tag:

  • Embed script code
  • Link JavaScript File

Embed script code

Just like embedded css, the script tag can be used within <body> or <head> tag to directly write the javascript code within the webpage. Have a look at the example below :


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> HTML Embed JavaScript </title>
</head>
<body>
<script type="text/javascript">document.write("This is a simple example of JavaScript.")
</script>
</body>
</html>

Output

HTML Embed JavaScript Examples

Link JavaScript File

The <script> tag can also be used to link an external script file by using src attribute. It is recommended to be used within the <head> tag only.

The external script is very useful when we have to use same script in more than one page. The script can be written in an external file, and then it can be added in any webpage where it is required.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> External JavaScript </title>
</head>
<body>
<script type="text/javascript" src="hello.js"></script>
<p id="demo"></p>
</body>
</html>

Output

Hello JavaScript!

The HTML noscript Element

The The <noscript> tag is used to provide an alternate content for users which have javascript disabled in their browser or if their browser doesn't support scripts.Look at the example to know more :


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> HTML noscript Element </title>
</head>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>
</body>
</html>

Output

HTML noscript Element Examples












Follow Us: