JavaScript is used to perform a certain task or chain of the task and execute it on the browser by changing the status of HTML DOMs

In the previous chapter of JavaScript Tutorials, we have learned about what JavaScript can do? Now we are about to learn that How and Where to use JavaScript on an HTML Document?

How to use JavaScript on HTML Documents?

Before we go forward we need to understand the most important thing and that is ‘How a web page is parsed on a web browser? This question is most important because until unless we don’t understand the working principle of a webpage, we can’t develop it with any client-side scripting language like JavaScript.

We already know that JavaScript manipulates the HTML DOM by changing its inner HTML, inner Text, values, and style. JavaScript is used to perform a certain task or chain of the task and execute it on the browser by changing the status of HTML DOMs. To do so we have to find and target the specific HTML DOM with various methods that we will learn in upcoming chapters. 

To understand the above sentences we need to check the below example.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of JavaScript</title>
</head>
<body>
    <div id="test"></div>
    <script>
        document.getElementById("test").innerHTML = "Hello World!";
    </script>
</body>
</html>
        
Try Yourself

What we see in the example above given. There are two things in the above example

The first thing we see there is an HTML document contains a DIV element with an attribute named ID. The value of the ID is ‘test’. We required printing Hello World inside the DIV element dynamically using JavaScript when a web page is loaded.

Second thing, there is also a script tag just before the end of body tag where are some codes are written which is not likely HTML codes. Actually the codes written in script tags are JavaScript. JavaScript codes are written between <script> tags on HTML documents.

Now to understand the working principle of the above example you can copy and paste the above code in your favorite HTML editor and save the file with .html file extension and run into your favorite browser. You will see ‘Hello World’ printed on the web page.

On the web page loading process, we simply target the HTML DIV tag by its ID using “document.getElementById()” method and setting the value ‘Hello World’ of its ‘innerText’ so that when the web page completely falls on the browser it prints ‘Hello World’ text.

This is how we target the HTML DOM on an HTML web page using JavaScript. This was only an example but in professional projects, we do something like this on a large scale. We will sure study that in this tutorial series.

 

Why & when use type attribute within <script> tags?

Now we know that JavaScript codes are written inside <script> tags. Let’s check a few another example given below

JavaScript codes with a type attribute in script tags


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Use of Type Attribute</title>
</head>
<body>
    <div id="test"></div>
    <script type="text/javascript">
        document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
    </script>
</body>
</html>
        
Try Yourself

JavaScript codes without type attribute in script tags


<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Example of HTML5 Version Doctype</title>
</head>
<body>
     <div id="test"></div>
     <script>
          document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
     </script>
</body>
</html>
Try Yourself

In both examples can you see the difference? You can see in example 2 <script> tag is used with type attribute and in example no 3 <script> tag is used without type attribute.

This is happening because of the HTML Document version. Before HTML version 5 JavaScript is not the default scripting language of HTML so we must specify the type of scripting language. Older browsers are not able to find the type of script language therefore JavaScript might not work.

But since HTML 5th version JavaScript is becoming the default scripting language, therefore, we are not forced to use type attribute in script tag while working with JavaScript.

Note: Above both examples can work in the latest browsers without type attribute. The problem comes with only older browsers.

Where to use JavaScript on HTML Documents?

Above all the examples are demonstrating to us how to use JavaScript on an HTML Document. Now let’s move on Where to use JavaScript on HTML Documents?

Before we go ahead first we need to understand how an HTML Document is parsed on a browser and become a web page.  Usually, HTML Document is parsed on a browser top to bottom and left to right. It means that the most top line of the document is parsed first into left to right direction therefore whole HTML DOMs must be parsed over web browsers before JavaScript functions are called.

If it doesn’t happen then the browser console will throw the script error and it can be case wise different. Another thing is that by default JavaScript declared functions and variables are stored on the top level in primary memory while launching the web page whether they are declared on top of page or bottom of the page, therefore, we should not worry about where we are trying to keep our JavaScript codes on HTML document. Therefore we can place JavaScript declared functions and variable between the <head> tags like the below-mentioned example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Declared Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button onclick="myFunction()">Click</button>
</body>
</html>
        
Try Yourself

We should worry about only JavaScript calling functions which must be executed at the most end of part of the web page so that All HTML DOMs can found easily found which are targeted by JavaScript. It is good practice to place JavaScript codes on the most bottom part of HTML <body> tags, mention like below example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Calling Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>

    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        
Try Yourself

Also, it is observed that placing JavaScript code at the bottom of <body> tags improves the display speed because script interpretation slows down the display.

Above shown examples are a type of internal JavaScript but there is another type of JavaScript also which can improve the development speed without harming the performance of the web site.

What are the types of placement of JavaScript on an HTML Document?

  1. Internal JavaScript
  2. External JavaScript

What is Internal JavaScript?

Internal JavaScript is a practice in which all the JavaScript codes are written separately in every document. The drawback of this practice is that we have to write a similar type of code again and again which slows down the development speed. All the above show examples are a type of internal JavaScript.

What is External JavaScript?

In this practice JavaScript codes are written in a separate file which has the file extension “.js”. To embed the external JavaScript file on the web pages we have to use <script> tags with a specific attribute named ‘src’ which holds the location path of the external JavaScript file.

Take a look at a below-given example. This example is created using jQuery CDN. You will learn jQuery in further chapters.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Absolute Path Over jQuery Content Delivery Network (CDN)</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        $(document).ready(function(){
            $('#test-button').click(function(){
            $('#test').html("Hello World!")
            });
        });
    </script>
</body>
</html>
        
Try Yourself

Few points must be noticed while creating an external JavaScript file.

  1. JavaScript file created with .js extension is not a web page rather a script page.
  2. JavaScript file cannot contain the <script> tags.
  3. Multiple JavaScript pages can be used on a single HTML document.
  4. It is important to declare the HTML web page doctype because before HTML5 JavaScript not default scripting language. We have to specify the ‘type’ attribute in <script> tags to make active scripting language.

What are the advantages of external JavaScript?

  1. HTML and JavaScript codes are separated while using external JavaScript
  2. JavaScript code which required to be executed again & again on different pages is not required to write multiple times.
  3. It makes developers easy to maintain and develop the program fast.
  4. You can use different specialist code editor at the same time. For example, Notepad++ is best for HTML, and VSCode is best suitable for JavaScript.
  5. External JavaScript code can be cached into the client device therefore cached JavaScript file can speed up the page load.

Using absolute and relative path reference for external JavaScript

 External JavaScript files can embed on HTML documents using relative or absolute path references which show below in the examples.

To understand relative or absolute file path learn HTML5 Tutorial - HTML File Path


//declared functions and variables
  var x = "You have clicked the button."
  function myFunction(){
  document.getElementById('test').innerHTML=x;
}
        


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of External JS file using absolute path</title>
    <script src="script.js"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        

Copy the JavaScript codes given in example 7 and paste into your favorite text editor and save as script.js and after that once again create a new file in the text editor and copy HTML codes from example 8 and paste into the text editor and save the document as 'example8.html'. Both the files must be located into same directory. 

After that run the example8.html file in the browser, you will see on the web page there is a button named 'Click'. When you click the button then a sentence 'You have clicked the button' will appear on the screen. This means the JavaScript codes written in a separate file is embedded properly and working fine.

On HTML file example8.html you can see <script> tag with 'src' attribute having the value 'script.js' which the name of JavaScript file. Actually the source of JavaScript is fetching on the web page from that file which is embedded with HTML document through a 'Relative path'.

Similarly, look back into example 6 where you can find <script> tag with 'src' attribute having a value 'https://code.jquery.com/jquery-3.5.1.min.js'. It is an example of an absolute URL. To know more about the relative and the absolute path you have to read our another topic HTML5 Tutorial - HTML File Path.

progrramers-logo

progrramers

Hello friends! Progrramers is a tutorial site of w3 programming. If you like this tutorial site please encourages us by sharing this site links with your friends and nears & dears who want to learn web development and give us like on our Facebook page. If have any question please type in to comment box or send us message on social media sites via below given social links. Thank you, have a nice learning.

Post A Comment:

3 comments:

  1. IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Projects for CSE It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    JavaScript Online Training in India

    JavaScript Training in India

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
  2. That being stated, a few of the much better translation firms will instantly make you knowledgeable about these truths as a matter of course; so if you called for a record translation in London the translation and interactive story localization business worried, could extremely well have these truths uploaded on their internet site as a politeness to their clients as eventually, it remains in every person's rate of interest to make certain that the task is done to the contentment of all celebrations.

    ReplyDelete
  3. The app has been well received and has increased both revenue and customer engagement for the client.
    Bay Area web design

    ReplyDelete