Sunday 30 September 2018

JavaScript: Writing script in external file

Till now, we are embedding the JavaScript code in the HTML file itself. There is another standard way also, you define all your JavaScript code in one file and import that file into HTML file using script tag.

Syntax
<script src="/path/to/script.js"></script>

As you see the sytax, you need to specify the path of JavaScript file in src attribute. JavaScript files are ended with extension .js.

Can I import multiple JavaScript files?
Yes you can import more than one JavaScript files

What is the best place to import the .js files?
Ideally you can import .js files from anywhere in the HTML document. Usually people prefer in two places.
a.   In the Head tag
b.   At the end of body tag
                          
Script file import from head tag
If you want the JavaScript to execute before loading the page, then keep it in head tag.

Scripts at the end of BODY
Most of the applications prefer this way. If you put JavaScript code at the end of the body, then script will execute once the page is loaded completely.

numbers.js
function printNumbers(){
 for(i=0; i < 10; i++){
  document.write(i + "<br />");
 }
}

printNumbers();

sample.html
<!DOCTYPE html>

<html>

<head>
    <title>Function Arguments</title>
</head>

<body>
    <h1>External JavaScript Example</h1>
    <script src="numbers.js"></script>
</body>

</html>

Open above page in browser, you can able to see following output.

External JavaScript Example
0
1
2
3
4
5
6
7
8
9





Previous                                                 Next                                                 Home

No comments:

Post a Comment