How to Add JavaScript in HTML with Example

Up to this point, we are now familiar with the basic introduction and history of JavaScript. In a web development project, two different kinds of scripting exist:

  • server-side
  • client-side

Server-side scripting is a script that runs on the web server, which sends results to your web browser. Some popular server-side scripting languages are PHP, Ruby, Python, and Perl.

Client-side scripting is a script that runs on the web browser without any interaction with the web server. The most popular client-side scripting language is Javascript.

In order to run client-side JavaScript, we must need to learn how to add or integrate JavaScript code in the HTML web page or document.

This is because we cannot place JavaScript statements in the HTML source code in just any location. So, let’s understand it.

How to Add JavaScript to HTML File

There are four standard different ways to add or embed JavaScript code in an HTML web page. In other simple words, JavaScript code can live in one of four locations within an HTML file.

  1. Directly in HTML page using a pair of <script> . . . </script> elements or tags
  2. As an event handler using HTML tag attribute.
  3. Via the pseudo-URL javascript: syntax within some link
  4. As a linked file with a .js extension via the src attribute of the <script> tag

How to add Javascript in HTML web page

So, let’s understand all ways one by one how to add JavaScript script into HTML file.

Within <script> Element or Tag

Every modern popular web browser has a JavaScript interpreter that interprets JavaScript code defined on the HTML web pages.

The primary method to place or add JavaScript within an HTML page is via <script> tag. The <script> tag is used to add (or insert) JavaScript code in HTML documents.

This tag was created by Netscape and first implemented in Netscape Navigator 2. We can place any number of <script> tags within a web page. All <script> tags are interpreted in the order in which they are specified on the page.

The general syntax to place JavaScript code within <script> element is as follows:

     // JavaScript statements go here.

For example:
       document.write("This is JavaScript code");

All statements written between the opening <script> tag and closing </script> tag are interpreted as JavaScript code (by default) from top to bottom.

This is because JavaScript is the default scripting language in common web browsers. Therefore, the Language attribute is not required to specify the scripting language.

Web browser loads the built-in JavaScript interpreter and then interprets the script code. This is probably the most common method for including JavaScript code into HTML web pages.

JavaScript is case-sensitive, but not HTML. So, It does not matter whether we write <SCRIPT> or <script>, but try to be alike.

Placing <script> tag in <head> Section

JavaScript program must start and end with <script> and </script> tags respectively within web page. Everything written inside these tags is assumed JavaScript code, nothing else.

The script tag can be placed anywhere inside an HTML web page. If you want to load and interpret JavaScript code before the user can begin using web page or the page is displayed, the <script> and </script> tags must be placed between opening <head> tag and closing </head> tag.

The <head> tag is a more appropriate place to embed JavaScript code. It is processed before the <body> tag.

The following example demonstrates how JavaScript code can be placed in the <head> tag of an HTML document.

Program code 1:

     <title>Script tags in the Head section </title>
        document.write("Placing <script> tag between <head> section");

In the preceding program, JavaScript code enclosed in the <head> section will display a message “Placing <script> tag between <head> section” on the web browser.

Placing <script> tag in <body> Section

JavaScript code inserted within <script> and </script> tags can also be placed just before the closing </body> tag if you want to load the script at the bottom of the web page.

On the other hand, if you want to execute script after loading full content on the web page, the script must be placed in between <body> …</body> portion.

The following example demonstrates JavaScript code snippet placed in the <body> of an HTML document.

Program code 2:

     <title>How to add JavaScript inside <body> tag</title>
       document.write("Placing JavaScript code in the <body> tag");

In the preceding example program, JavaScript code enclosed between <body> section will display a message “Placing JavaScript code in the <body> tag” on the web page.

All the Javascript code in the <head> section must be downloaded, parsed, and interpreted before the web page starts rendering.

A web page that contains a lot of JavaScript code, can cause a delay of a millisecond to execute codes during page rendering by the browser. During this time, the browser will show the blank page.

For this reason, modern web applications typically insert all JavaScript code snippets in the <body> tag, after the page content.

We can place an unlimited number of <script> tag in an HTML document. The below example illustrates a script in both head and body sections of HTML page.

Program code 3:

     <title>Scripts in both head and body tags</title>
      document.write("This is JavaScript code placed in <head> tag");
        document.write("This is JavaScript code placed in <body> tag");
      This is JavaScript code placed in <head> tag
      This is JavaScript code placed in <body> tag

Attributes Added to <script> Element

There are six attributes available for adding within <script> element. Most of the modern browsers support these attributes. They are as follows:

  • async
  • charset
  • defer
  • language
  • src
  • type

1. async:

The async attribute was introduced in HTML5. It signals the browser to load the script asynchronously without blocking anything during rendering the web page. It is valid for only external JavaScript script files.

The following examples show the use of async in the <script> tag.

<script src = "myScript1.js" async></script>
<script src = "myScript2.js" async></script>

As you can see in the above examples, the use of async attribute within script tag is very simple.

2. charset: It is also optional. The character set of the code is specified using the src attribute within the script tag. This attribute is seldom used in the script tag because most browsers don’t honor its value.

3. defer: This attribute was introduced in HTML4. It tells the browser to defer the execution of script safely until after the document’s content has been completely parsed and displayed on the web page.

The defer is valid only for external scripts. Deferred scripts always run in the order in which they are written in the code.

The following examples demonstrate the use of defer attribute in the script tag.

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

4. language: This attribute is deprecated. Originally, it tells theweb browser about scripting language being used by the code block such as “JavaScript”, “JavaScript1.2”, or “VBScript”. Most browsers ignore this attribute and should not be used.

5. src: This attribute tells the browser about an external JavaScript file that contains code to be executed. It is optional.

6. type: This attribute tells the browser about the content type (also called MIME type) of the scripting language being used by the code block.

Traditionally, this value has always been “text/javascript”. The value of type attribute is still “text/javascript” by convention and for maximum browser compatibility. This attribute is safe to skip because it is assumed “text/javascript” when missing.

Executing JavaScript using Event Handler

To make a web page more interactive, we can also add Javascript code into an event handler using HTML tag attribute. It is the second way to execute JavaScript code via an event handler.

We define an event handler to trigger the execution of script in response to user activity such as a form action, key press, or mouse movement.

With an event handler, JavaScript will execute when an event occurs. A good example of an event handler is an image rollover, where an image alters when the mouse pointer moves over it.

Some commonly used event handlers are onClick, onSubmit, onLoad, onMouseOut, and onMouseOver. All event handler attributes start with the word “on”.

The following code is a simple example of an event handler where we will click on a button, Javascript code will execute.

Program code 4:

<DOCTYPE html>
       <title>Event Handler Example</title>
      <input type = "button" value = "press me" onclick = "document.write('Hello JavaScript!');"/>

This is a simple example of event handler. When you will run the code and click on the button, it will display a message “Hello JavaScript!” on the screen.

We will know more concepts with examples in Event handler chapter in the further tutorial.

Executing JavaScript Code using Javascript Pseudo URL

A pseudo URL is the third way to call JavaScript code in most JavaScript-aware browsers. It is a new URL style in the form Javascript: that introduces a new technique for incorporating JavaScript into a web page.

When the URL that begins with javaScript: is loaded on the web page then the code behind that is executed.

Let’s understand the concept of JavaScript pseudo-URL with the help of a simple example.

Program code 5:

<DOCTYPE html>
       <title>An Example of JavaScript Pseudo-URL</title>
       <a href = "javaScript: document.write('Hello I am a pseudo-URL script');">Click on me</a>

When a user clicks on the link that begins with javaScript: then the code behind that is executed. The following output will display on the web page after the execution of JavaScript code.

Output of code:
          Hello I am a pseudo-URL script

As you can see in the above code, the value of href attribute is not a standard URL. It contains javaScript code. The value begins with javaScript: which specifies a pseudo URL link.

The javaScript: in the link tells the browser about javascript code. The web browser then executes javaScript code that follows javascript: in the link.

Here, Pseudo indicates that it is not actually a protocol like HTTPS, HTTP, or FTP but it works in the same way.

Hope that this tutorial has covered almost all the important points related to how to add JavaScript in HTML web page. I hope that you will have understood the basic concepts of adding javaScript code to HTML file.

In the next tutorial, we will discuss how to add external JavaScript file in HTML page.
Thanks for reading!!!
Next ⇒ How to include External JavaScript in HTML⇐ Prev Next ⇒

Please share your love