.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. 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");
x.style.fontSize = "25px";
x.style.fontFamily = "Verdana";
x.style.color = "black";
x.style.backgroundColor = "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.