Tutorials » Javascript tutorials »

Calling JavaScript from some other page


This article explains about calling Javascript from an external file.


JavaScript that is in other files is called external JavaScript.

External JavaScript can be called using src attribute of script tag.

Syntax as follows:



<html>

<head>

<script src="ExternalFile.js"></script>

</head>

<body>

</body>

</html>



Where this is exactly fit in real time?



If you want to do a required field validation (making to enter/select for particular control as mandatory) for 10 pages, what you will do probably. The same validation needs to be fired in 10 webpages. We can avoid this by using calling external script.


Advantages?



1.Reusability since don’t need to place the code in HTML documents.

2.If there is a kind of change in validation then we don’t need to change code in all webpages.

3. It secures precious code.

Go to view ?source in browser your validation code can’t be seen .

Example



Type the following code in note pad and save with extension as .js (external.js)



function f()

{

alert(‘calling External JavaScript’);

}



External.Html




<html>

<head>

<script src ="external.js"></script>

</head>

<body>

<input type = "button" value ="click" onclick ="f();">

</body>

</html>



Execution



When ever a button is clicked it checks for the function in script tag. Control goes to source tag and calls external.js file. In that file it checks for the function f(). The corresponding coding in f() is displayed in browser. So the same script can be called in different we pages .Many functions can be placed in JavaScript external file.

Where to Use script in the body or header?



A <script src="url"></script> blocks the downloading of other page components until the script has been identified, compiled, and executed. So It is better to call for the script as late as possible. If there are images or other components that will not be delayed. So it is usually best to make all <script src="url"></script> the last features before the </body>.

If a script is defining functions that are used by some other functions, then it is better to define it before use.






Next Chapter: JavaScript Objects
Previous Chapter: A simple login Validation with JavaScript
More Chapters: Javascript Tutorials
More Tutorials: Tutorial Index



Top Contributors
TodayLast 7 Daysmore...

Awards & Gifts

Online Members

inco
More...
 
Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India