Add JS to HTML

Last updated on

The development of full-featured and interesting pages cannot be done without JavaScript which makes it possible to animate plain HTML and offer even more functionalities for users.

In this tutorial, we will explain how we can add JS code to a page step by step, or more precisely, how to start using JS in any HTML project.

Before getting started, you might want to understand how JavaScript works internally.

In the next two paragraphs, you will acquire more than one method of embedding JavaScript code within an HTML document. Let us examine all of them one by one.

Understanding the <script> Tag

The <script> tag is an HTML element used to embed or reference external JavaScript code inside an HTML document. It can be attached in an HTML document inside either the <head> section or <body>, depending on what one would like to do with the particular code.

Let’s move on to the following section to understand how to embed JavaScript code using the <script> tag.

Embedding JavaScript Code Using the <script> Tag

To embed JavaScript using the <script> tag, follow this basic syntax:

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

Let’s see its position within the HTML document.

Placement within HTML

In the <head> Section: The <script> tag for the script that needs to be executed before the complete page loads should be placed in the <head> section.

This can contain functions to initialize variables, set configurations, or perform any other activity the execution of which is necessary to render the page correctly.

<head>
  <script>
    // Initialization code
  </script>
</head>

Before the Closing </body> Tag: Placing the <script> tag just before the closing </body> tag is ideal for code that should execute after the HTML content has loaded. This approach helps improve page loading performance.

<body>
  <!-- HTML content goes here -->
  <script>
    // Code that interacts with HTML elements
  </script>
</body>

Most JavaScript developers use the externalizing method to include JavaScript files. Let’s see how it works.

Externalizing JavaScript for Clean Code

To keep your HTML clean and maintainable, it’s common practice to store JavaScript code in separate files with a “.js” extension. For example:

<html>
  <head>
    <title>Your Page</title>
    <script src="script.js"></script>
  </head>
  <body>
    <h1>Hello, World!</h1>
  </body>
</html>

Here, the JavaScript code is saved in a file named “script.js,” and the script tag references this external file. This approach promotes code reuse and organization.

In another way, you can also put the <script src='..'> before the closing of the HTML body tag: </body>.

<html>
  <head>
    <title>Your Page</title>
  </head>
  <body>
  
    <h1>Hello, World!</h1>
    
    <!-- The external js file here -->
    <script src="script.js"></script>
    
  </body>
</html>

In the following section, you will learn how to optimize file loading on a web page through the use of the ‘async’ and ‘defer’ attributes.

Asynchronous Loading

When including external JavaScript files, you can specify whether the script should load synchronously or asynchronously. Asynchronous loading enhances page performance by allowing other page elements to load simultaneously. Example:

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

Using the async attribute tells the browser to continue parsing the HTML while simultaneously fetching and executing the script.

Let’s move to the ‘defer’ attribute

Defer Attribute

Another way to optimize page loading is by using the defer attribute. This attribute ensures that the script is executed only after the HTML has been fully parsed. Example:

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

Unlike async, the defer attribute guarantees the order of script execution and is well-suited for scripts that depend on specific elements in the HTML.

Once you’ve finished your awesome code, let’s execute it through a simple event.

Ensuring Seamless Execution

Understanding the flow of execution is pivotal. JavaScript commands within <script> tags are executed sequentially during the page load. For more precise control, harness event listeners to trigger specific actions when users interact with your webpage.

<!-- Triggering JavaScript on button click -->
<button onclick="greet()">Click me</button>

Wrapping Up

In conclusion, this guide has delved into the intricacies of seamlessly integrating JavaScript into HTML, unlocking the potential for dynamic and interactive web pages. By understanding the <script> tag and its placement within HTML, developers gain flexibility in optimizing the execution of their code.

Whether embedding JavaScript directly within the HTML document or externalizing it into separate files, the guide has explored various techniques. Placing scripts in the <head> section ensures pre-loading functionalities, while situating them before the closing </body> tag enhances page loading performance.

Externalizing JavaScript, a practice of storing code in separate files, contributes to clean and maintainable HTML. By referencing external files using the <script src='..'> tag, developers promote code reuse and organization.

The guide also touched upon asynchronous loading and the use of attributes like “async” and “defer” to enhance page performance. Asynchronous loading allows scripts to load simultaneously with other page elements, while the “defer” attribute ensures sequential execution post-HTML parsing, beneficial for scripts dependent on specific elements.

Understanding the flow of execution is crucial, and the guide emphasizes the use of event listeners for precise control. With a snippet showcasing the triggering of JavaScript on a button click, developers can harness this knowledge to create seamless user interactions.

In essence, by grasping the nuances of incorporating JavaScript into HTML, developers are equipped to build dynamic, efficient, and user-friendly web pages. As you embark on your coding journey, consider these practices to optimize your code structure and enhance the overall performance of your web projects.

Share on: