JavaScript - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript Files

JavaScript Files

shape Description

The best and the most useful way to utilize JavaScript code is by using External files. There are three main reasons for using external JavaScript files, they are:

shape Conceptual Figure

shape More Info

The extension for external JavaScript files is .js The code from an external file can be included using source (src) attribute. The value of src is a URL linked to a file containing JavaScript code as shown below: [c]<script type="text/javascript" src="example.js"></script>[/c] The browser loads demo.js file.

shape Examples

The following example.html file depicts the extfile.js javascript file using src attribute. [html] <!DOCTYPE html> <html> <head> <title>External file example</title> </head> <body> <h1 style = "color: green">SPLessons </h1> <p id="test" style="color:blue">JavaScript Tutorial</p> <button type="button" onclick="myFunction()">Click it</button> <p><strong>Note:</strong> myFunction is stored in an external file called "extfile.js".</p> <script src="extfile.js"></script> </body> </html> [/html] The following is extfile.js file. [html] function myFunction() { var x = document.getElementById("test"); = "25px"; = "Verdana"; = "black"; = "cyan" } [/html] When the example.html file is loaded by the browser, the below output can be seen on the screen: When the button "Click it" is pressed, the function "myFunction" present in "example.html" will be called and stored externally in "extfile.js", which is nothing but the JavaScript file. Likewise, JavaScript file can be called any number of times and used.


shape Key Points

  • External files differentiate HTML and JavaScript codes.
  • src attribute is used to link the JavaScript file.