Use Multiple JavaScript Files in Coordination with each other

Started by ganeshbala, Aug 19, 2008, 10:29 AM

Previous topic - Next topic

ganeshbala

Use Multiple JavaScript Files in Coordination with each other

Save your commonly used JavaScript code functions in a file with a .js extension. In this example, we will save them in a file called sample1.js:
function myFunction() {
alert('Hello world');
}
function yourFunction() {
alert('Goodbye world');
}


Save your JavaScript code that actually calls these functions in another file, in this example sample2.js. Example:
myFunction();

Now in your HTML page, source both files in the proper order. All function definitions should come before the function calls. Example:


My page


This will print the myFunction alert window to your browser.


Another page can reuse the sample1.js functions, but call them differently. Create sample3.js with the contents:
yourFunction();


In the second HTML page, your function file sample1.js is reused:


Your page


therefore reusing your functions and coordinating your JavaScript files.