How to add JavaScript to HTML

JavaScript, often abbreviated as JS, serves as a client-side scripting language commonly applied in web development for crafting dynamic and engaging web pages. The term "scripting" denotes languages that are not autonomous, and in this context, it specifically pertains to JavaScript, which executes on the client's device.

In essence, scripting refers to languages that need the assistance of another language to be executed. For instance, the execution of JavaScript programs depends on HTML or their integration into HTML code.

JavaScript serves various purposes on web pages, including displaying alert messages, creating photo galleries, manipulating the Document Object Model (DOM), validating forms, and other functionalities.

Adding JavaScript to HTML Pages

There are three ways in which users can add JavaScript to HTML pages:

  • Embedding code
  • Inline code
  • External file

We will see three of them step by step.

I. Embedding code

To add the JavaScript code into the HTML pages, we can use the <script>.....</script> which can be placed in either the <body> tag (or we can say body section) or the <head> tag because it completely depends on the structure of the web page that the users use

A clearer understanding of incorporating JavaScript into HTML can be achieved through the assistance of an illustrative example.

Example

Example

<!DOCTYPE html>  

<html>  

<head>  

<title>Page Title</title>  

<script>  

document.write("Welcome to our tutorial");  

</script>  

</head>  

<body>  

<p>In this example, we saw how to add JavaScript in the head section.</p>  

</body>  

</html>

Output:

Output

Welcome to our tutorial

In this example, we saw how to add JavaScript in the head section.

Explanation:

Within this HTML snippet, you can observe the incorporation of JavaScript into a specific part of the document. By utilizing the document.write method within the <script> element, a notification "Welcome to our tutorial" is presented directly on the webpage upon its loading, preceding the body content. Additionally, the body paragraph clarifies the inclusion of JavaScript within the head section.

One alternative is to specify the JavaScript code within the <body> tag or within the body section of the document.

Let's understand through an example.

Example

Example

<!DOCTYPE html>  

<html>  

<head>  

<title> page title</title>  

</head>  

<body>  

<script>  

document.write("Welcome to our tutorial");  

</script>  

<p>In this example, we saw how to add JavaScript in the body section.</p>  

</body>  

</html>

Output:

Output

Welcome to our tutorial

In this example, we saw how to add JavaScript in the body section.

Explanation:

The following HTML snippet showcases the integration of JavaScript directly within the <body> segment of a webpage. In this instance, the <script> element leverages the document.write method to display the greeting "Welcome to our tutorial" immediately upon the page's loading. This prompt is exhibited prior to the paragraph content due to the script's execution during the page's loading process.

II. Inline code

Typically, this approach is employed when there is a need to invoke a function in the HTML event attributes like the onmouseover event or the onclick event. Upon clicking the "Click Me" hyperlink, an alert dialog will pop up showing the text "Welcome!".

Let's explore an illustration of incorporating JavaScript code directly within the HTML document without the need for the <script> tag.

Let's look at the example.

Example

Example

<!DOCTYPE html>  

<html>  

<head>  

<title> page title</title>  

</head>  

<body>  

<p>  

<a href="#" onclick="alert('Welcome !');">Click Me</a>  

</p>  

<p>In this example, we saw how to use inline JavaScript or directly in an HTML tag.</p>  

</body>  

</html>

Output:

Once the "Click Me" button is clicked, an alert box will appear on the screen.

Explanation:

The provided code demonstrates the utilization of inline JavaScript, where a script is connected directly to an HTML element through an onClick attribute. Upon clicking the "Click Me" link, an alert box will display a greeting message saying "Welcome!". The subsequent section clarifies that this serves as an illustration of inline JavaScript usage.

III. External file

Another approach is to generate a distinct JS file where the JavaScript code is stored with the (.js) extension. This file can then be integrated into the HTML document by using the src attribute of the <script> tag. This method is beneficial when there is a need to utilize identical code across various HTML documents. Furthermore, it eliminates the necessity of repeatedly writing the same code, streamlining the process of managing web pages.

In this instance, we will demonstrate the process of integrating an external JavaScript file into an HTML document.

Let's understand through a simple example.

Example

Example

<!DOCTYPE html>

<html>  

<head>  

<meta charset="utf-8">  

<title>Including External JavaScript File</title>  

</head>  

<body>  

<form>  

<input type="button" value="Result" onclick="display()"/>  

</form>  

<script src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image"></script>  

</body>  

</html>

Now let's create a separate JavaScript file.

hello.js

Example

function display() {  

alert("Hello, World!");  

}

Output:

Once the Result button is clicked, an alert box will be displayed.

Explanation:

The following HTML code demonstrates the process of connecting an external JavaScript file using the <script src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image"> element. Within the webpage, there is a form featuring a button labeled "Result". Upon clicking this button, the execution of the display function from the hello.js file is initiated. The display function's purpose is to showcase an alert box that presents the text "Hello World!". This instance emphasizes the advantages of maintaining a distinction between JavaScript and HTML, resulting in enhanced code structure and reusability.

It is necessary to save both the HTML and JavaScript files within the same directory. Alternatively, you have the option to place the JavaScript code in a distinct folder; however, you must only specify the location or path of the (.js) file in the src attribute.

Benefits of External JavaScript

  • Faster Page Loading Speed: External JavaScript files are cached by the browser so they are not reloaded every single time we visit the page (can help load faster).
  • Easier to Read and Maintain: It is easier to read and maintain the code when HTML and JavaScript are separated out.
  • Improved Separation of Concerns: Your code will be cleaner and more modular when you separate HTML (structure) from JavaScript (behavior).
  • Code Reusability: We can link a single external JavaScript file to multiple documents, which reduces duplication and makes it easier to make updates.
  • Asynchronous and Deferred JavaScript

To optimize the loading performance of a webpage, particularly with larger scripts, JavaScript can be asynchronously or deferredly loaded. By default, JavaScript inclusion in an HTML document halts the page rendering until the script is fully loaded. However, utilizing the async or defer attributes can enhance performance and expedite the loading time of the page.

Using the async attribute when loading a script allows it to be fetched and run without delaying the page load, enabling it to execute as soon as it's ready.

Example

<script src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" async></script>
  1. defer Attribute

The defer attribute delays the execution of the script until after the HTML document has finished parsing, which is particularly beneficial for scripts that interact with the Document Object Model (DOM).

Example

<script src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" defer></script>

The HTML noscript Element

The <noscript> element offers an alternative method for generating content for individuals whose browsers lack JavaScript support or have it deactivated.

The element is capable of accommodating any HTML element except for the <script> tag within the <HTML> element.

To gain a clearer understanding, let's delve into an illustration:

Program

Example

Example

<!DOCTYPE html>    

<html>    

<body>    

<h1>The noscript element</h1>    

<p>If the user has a browser with JavaScript disabled then the text inside the noscript element and "Hello World!" will not be displayed.</p>    

<script>    

document.write("Hello World!");   

</script>    

<noscript>Sorry, your browser may not support JavaScript or it might be disabled in your browser.</noscript>       

</body>    

</html>

Let's observe the result produced upon executing the aforementioned program in a browser that supports JavaScript.

Output:

Next, let's observe the result that will be generated by executing the identical program in a browser with JavaScript disabled or in a browser that lacks JavaScript support.

Explanation:

Within the program mentioned earlier, JavaScript was employed to display the text "Hello World!" and to utilize the <noscript> element for outputting the message "Sorry, your browser might not have JavaScript support or JavaScript could be deactivated in your browser". The display of this message through the <noscript> element is conditional on the absence of JavaScript support in the user's browser or if JavaScript is disabled.

Example

Example

<!DOCTYPE html>  

<html lang="en">  

<head>  

<meta charset="utf-8">  

<title>Noscript Demo</title>  

</head>  

<body>  

<div id="greet"></div>  

<script>  

document.getElementById("greet").innerHTML = "Hello World!";  

</script>  

<noscript> <!--This element will print the given message only when the execution of the <script> tags does not take place.  -->

<p>Oops! This website requires a JavaScript-enabled browser.</p>  

</noscript>  

</body>  

</html>

Execute the program above in a browser that supports JavaScript.

Output:

Output

Hello World!

Next, execute the aforementioned program on a browser that has JavaScript disabled.

Output:

Output

Oops! This website requires a JavaScript-enabled browser.

Explanation:

The following HTML code shows how the <noscript> tag functions to present alternative content when JavaScript does not run in the user's browser. The page contains a <div> element with the ID "greet" , where JavaScript is used to inject the text "Hello World!" into the page. When JavaScript is disabled then the browser will show the elements inside the <noscript> tag which includes a notification stating that the user needs a browser that supports JavaScript.

Conclusion

In summary, incorporating JavaScript into an HTML file is a crucial process for enhancing the interactive features and capabilities of websites.

There are three primary ways to add JavaScript: inline, internal, and external .

  • With inline JavaScript , you place the script directly into HTML elements using event attributes , though inline JavaScript is only the best practice for very simple, small interactions.
  • The second option is to include internal JavaScript , which allows you to add JavaScript in <script> tags in your HTML document . Internal JavaScript is best for modest to larger-sized scripts.
  • The third option is external JavaScript , which is the best option for larger projects. Using external JavaScript allows you to keep cleaner code and organize your JavaScript outside of the project by linking separate .js files using the src

The techniques outlined demonstrate the integration of JavaScript into an HTML file and its applications. While each method serves its purpose, external JavaScript is typically considered the preferred approach for scalability and ease of maintenance in the majority of web development endeavors.

Frequently Asked Questions (FAQs)

  1. What is the most effective method for incorporating JavaScript into my HTML document?

An ideal approach is to reference an external JavaScript file by using the defer attribute on the script tag, which will be placed immediately before the closing body tag (e.g., <script src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" defer></script>).

  1. Should I put JavaScript in the head or body?

The <script> tags for your JavaScript should be placed at the end of the <body> section, right before the closing </body> tag.

When you place scripts in the <head>, the page has to wait until those scripts are fully downloaded and run before anything is displayed. This results in users seeing a blank white screen, which is quite a poor user experience. When scripts are placed at the end of the <body>, the HTML and CSS can be rendered first, so users see the content a lot quicker.

  1. Can I add multiple script tags in one HTML file?

Certainly, it is possible for a solitary HTML document to encompass multiple instances of <script> elements. These elements will be fetched and executed by the browser in a sequential manner, following the order in which they are presented within the document.

This method is commonly used to preload external libraries before loading scripts that depend on them.

Example

<body>

    <script src="https://placehold.co/400x300/9b59b6/ffffff?text=Sample+Image"></script> 

    

    <script src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"></script> 

</body>
  1. What distingushes the async attribute from the defer attribute?

Attributes for loading scripts without affecting page rendering are defer and async. The key contrast lies in the execution order: defer ensures scripts run in the sequence they appear after the document parsing is complete, whereas async allows scripts to execute as soon as they are downloaded, potentially in a non-sequential order.

How can debugging be performed on non-functional JavaScript code?

Access the Developer Tools in your browser by pressing F12, then navigate to the Console tab to review any error messages. Check the Network tab to confirm that the files are being loaded properly, and include console.log statements in your code to monitor the values of variables.

Input Required

This code uses input(). Please provide values below: