Javascript Implementation

Javascript is a dynamic client-side scripting language for creating interactive web pages. To initialize Javascript code in a web page first we have to include the Javascript source code in that page.

To do this, Javascript uses an HTML tag called <script></script>

The <script> Tag

The only way you can insert Javascript code in HTML web pages is to use <script></script> tag in the </head> or </body> section.

Javascript code can be inserted into a web page using two methods. (i) Inline Javascript and (ii) External Javascript

(1) Inline Javascript

<script>
    //Javascript code goes here
</script>

Using the inline method, all the Javascript code goes into the <script></script> tag.


You can put that script in the <head/> or <body/> section. Both will work.

Example: Inserting in </head> tag

<!DOCTYPE html>
<html>
<head>
    <script>
        //Javascript code goes here
    </script>
</head>
<body>

        //HTML elements and contents

</body>
</html>

Or inserting in </body> tag

<!DOCTYPE html>
<html>
<head>
    //Head content goes here
</head>
<body>

        //HTML elements and contents
        <script>
            //Javascript code goes here
        </script>

</body>
</html>

Putting Javascript in </body> tag can help to speed up your page loading time. Because browser renders the content as the code written sequence. So other content will be load before executing the Javascript code.

(2) External Javascript

By using the following tag and syntax you can include an external Javascript file to function the page.

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

In the above code, the src attribute refers to an external Javascript file in the right path. Now we need to create an external Javascript file and name it to myscript.js, remember every Javascript file must end with .js file extension.

Example: myscript.js

Using any text editor, write down the code and save that as myscript.js. Then keep that in the index root folder to work with the above HTML page.

function myFunction() {
 document.getElementById("demo").innerHTML = "Hello, PrograCoding!";
}

Note: External Javascript files do not contain <script></script> tag

Similarly, you can implement external Javascript in both </head> and </body> section. For multiple javascript files, define multiple </script> tags and their path.

Advantage of External Javascript

Placing Javascript outside of an HTML page has many advantages that implementing inline Javascript.

  • Speed up page loads and keep the HTML page clean.
  • Separates HTML and Javascript code
  • You can reuse the same script in multiple pages.
  • Separate Javascript file can be cached. So that, cached file reduce load time.

« Previous Next »