Home » javascript » JavaScript Inclusion in HTML File

JavaScript Inclusion in HTML File

Javascript in Internal File

  1. You can place JavaScript code on HTML pages anywhere within<html> tags(within <body>tag as well as <head> tag)
  2. JavaScript code must be inside <script> tag for aninternal placement.

Within <head> tag

Within <body> tag

External JavaScript

To use JavaScript from an external file source, all JavaScript source code must be written in a text file with the extension “.js” and then include that file as shown below:

For example, if the following content is already written in the file_name.js file the function  Show can be invoked in your HTML file after including the file_name.js file.

Note: The correct path (using ./ or ../ in front of the filename in src attribute) should be mentioned while including the external .js file otherwise it will throw an error and the file will not be included into the current HTML script.

External JavaScript Advantages

Placing scripts in external files is more advantageous than that of in an internal file:

  • It separates HTML and JavaScript code
  • It makes both HTML and JavaScript code easier to read and maintain
  • Cached JavaScript files can speed up page loading

Absolute Path

External scripts can be included with a full URL which is known as Absolute path. Consider the following example:

<script src=”https://www.abcd.co.in/js/file_name.js”></script>

Relative Path

External scripts can also be referenced with a path relative to the current web page which is known as Relative path. Consider the following example:

<script src=”/js/file_name.js”></script>

Managed by MochaHost - Fast & Easy WordPress Hosting