Where to use JavaScript Code in the HTML Pages (External JavaScript)

External JavaScript File to an HTML Document
JavaScript code is placed in external files. The file extension of JavaScript files have .js
To use an external JavaScript file, put the name of the script file in the src (source) attribute of a <script> tag:
<script src="scripts.js"></script>
Example: The Html Page should be like the following.
<!DOCTYPE html> 
<html> 
<head> 
<style> 
body{ 
background-color: gray; 
</style> 
<script src="script.js"></script>
</head> 
<body> 
<h2>JavaScript code in Head section</h2> 
<p id="appliedID">Predefined Paragraph.</p> 
<button type="button" onclick="newFunction()">Click</button> 
</body> 
</html>
Example: The Script Page should be like the following with name "script.js".<script> 
function newFunction() { 
document.getElementById("appliedID").innerHTML = "New applied paragraph after button clicked."; 
 
Note: You can place an external script reference in <head> or <body> as you like and External scripts cannot contain <script> tags.
Result: 
External JavaScript Advantages
External files has some advantages:

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

To add several script files to one page  - use several script tags:
<script src="script1.js"></script> 
<script src="script2.js"></script>
This example uses a full URL to link to a script:
<script src="https://www.tutorialspointbangla.blogspot.com/js/script1.js"></script>
This example uses a script located in a specified folder on the current web site:
<script src="/js/script1.js"></script>
This example links to a script located in the same folder as the current page:
<script src="script1.js"></script>
In the following video, i have discuss about External JavaScript.
HTML source code:
<!DOCTYPE html> 
<html> 
<head> 
<script src="js.js"></script> 
</head> 
<body> 
<h2>The way to Include External JavaScript Code</h2> 
<p id="demo"></p> 
<button type="button" onclick="myFunction();">Include External JavaScript</button> 
</body> 
</html>

JavaScript Source Code:
function myFunction(){ 
document.getElementById("demo").innerHTML = "Hello! I'm External javascript"; 
}


EmoticonEmoticon