learn javascript js

Different ways to include JavaScript in HTML and its Purpose

This tutorial guides on how to include JavaScript in HTML in different ways. In this tutorial we also will see how to use an external .js file in html file.

Different ways to include JavaScript in HTML

Usually, JavaScripts are used either in the <head> or <body> section of the page, so that they are available and ready to run when the pages finishes loading in the browser. The following is an example to show how to add javaScript <script> section in your HTML code.

<!DOCTYPE html>

<head>
<title>Web Page Title</title>
<script type="text/javascript">
JavaScript code here
</script>
</head>

<body>
<script type="text/javascript">
JavaScript code here
</script>
Page text and XHTML...
</body>

</html>

The script sections in the page is surrounded by a <script> tag containing the attribute type=”text/javascript” is used to identify this section of the page as containing script code written in the JavaScript language.

Purpose of scripts in the <head> section:

When you place a script inside the <head> section, it will ensure that the script will be loaded before anyone uses it. And whenever you want the scripts to be executed when they are called or when an event is triggered then that script should go in to the <head> section.

Purpose of scripts in the <body> section:

When you place a script inside the <body> section it will generate the content of the page. And whenever you want the scripts to be executed when the page is loading, then the scripts should go in to the <body> section.

How to use external .js (JavaScript) file in HTML ?

Using an external .js (JavaScript) file is another way to include JavaScript in HTML. Using this option you need to mention the full path of the JavaScript file within the <head> section. And make sure that the external .js file has all the required javascript functions written. The following the example for including external .js file.

<head>
    <script type="text/javascript" src = "<path to your .js file>"></script>
</head>

Also See:

References:

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments