Friday 2 February 2018

How to use an external JavaScript file in HTML code

When the JavaScript code is very lengthy we can place it in an external file and save that file with the .js extension. We then need to link the external file with HTML document by using the src attribute
of  the SCRIPT element to access that file.
Now We create a Web page named ScriptInExternalFile.html which shows how to use an external JavaScript file.

Shows the code for the  ScriptInExternalFile.html file.

<!doctype html>
<html>
<head>
<title>Using the External script file</title>
</head>
<body>
<h2>The sum of First Four Number is :</h2>
<h2><script src="MyScript.js"></h2>
</script>
</body>
</html>

Here We creates a Web page that prints the sum of four numbers, however it does not contain the code used to generate the sum. The code used to generate the sum is the script code that resides in the external file named MyScript.js. In the ScriptInExternalFile.html file the src attribute of the SCRIPT element is used to link the HTML document with the external script file MyScript.js. When the page loads the browser reads the URL of the external file to execute it and returns the output of the file to the page. Now create a file named MyScript.js which contains the code to produce the sum of four numbers.

Showing the Code for the MyScript.js File.


var i, count=0;
for(i=0;i<5;i++)
{
count=count+1;
}
document.write(count);

Here the external script file does not contain the SCRIPT element. the code written in the MyScript.js file declares two variables, i and count and initializes the count variable by zero. Then the for loop executes four times and each time adds the value of i in the count variable. After that the value of count variable is displayed on a Web page.

Shows the output of the ScriptInEternal.html file





No comments:

Post a Comment