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:
Example: The Html Page should be like the following.
Example: The Script Page should be like the following with name "script.js".<script>
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:
To add several script files to one page - use several script tags:
This example uses a full URL to link to a script:
This example uses a script located in a specified folder on the current web site:
This example links to a script located in the same folder as the current page:
document.getElementById("demo").innerHTML = "Hello! I'm External javascript";
}
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>
<!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>
function newFunction() {
document.getElementById("appliedID").innerHTML = "New applied paragraph after button clicked.";
}
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>
<script src="https://www.tutorialspointbangla.blogspot.com/js/script1.js"></script>
<script src="/js/script1.js"></script>
<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