Javascript in Internal File
- You can place JavaScript code on HTML pages anywhere within<html> tags(within <body>tag as well as <head> tag)
- JavaScript code must be inside <script> tag for aninternal placement.
Within <head> tag
1 2 3 4 5 | <head> <script language="JavaScript" type="text/javascript"> //JavaScript code </script> </head> |
Within <body> tag
1 2 3 4 5 | <body> <script language="JavaScript" type="text/javascript"> //JavaScript code </script> </body> |
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:
1 2 3 4 5 6 7 8 | <html> <head> <script language="javascript" type="text/javascript" src="file_name.js"></script> </head> ....... </html> |
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.
1 2 3 | function Show(){ alert("Hey there! I’m using JavaScript") } |
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>