Javascript needs to be included in a web page so that it is successfully executed. Any javascript to be executed should be included inside <script></script> tags. When browser encounters <script> tag, it knows that the statements written between the opening and closing script tags are not to be treated as HTML.
<script> tag has below optional attributes:
1. Type: Its value is text/javascript.
2. Language: Its value is javascript.
3. src: Source attribute, required when javascript from an external file is imported as explained next. Example,

<script type=”text/javascript” language=”javascript”>
// javascript code
</script>

Inclusion
There are two ways in which javascript code can be included in a web page.
1. Inline inclusion
Include <script> tag along with the code to be executed on the web page itself. Though it can be included anywhere on the page but the recommended approach is to add it at the bottom of the page. Example,

<html>
   <head>
      <!-- HTML code -->
   </head>
   <body>
      <!-- HTML code -->
   <script>
      // javascript code
   </script>
   </body>
</html>

Reason for including it the end is that it allows the page to be loaded first after which the script is executed which does not hamper page load time.
2. External File
It is also possible to place javascript code in an external file and including it in the web page. This is convenient when javascript code is of significant lines which if included in a page would cause cluttering.
Second advantage is that placing javascript code in an external file allows it to use it in multiple web pages promoting code reusability and preventing code duplication.
This method makes use of src attribute of <script> tag. Syntax to include an external javascript file is

<html>
   <head>
      <!-- HTML code -->
   </head>
   <body>
      <!-- HTML code -->
   <script src="externalScript.js">
      // javascript code
   </script>
   </body>
</html>

Note that javascript file should be saved with .js extension.

1

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.