Places to put JavaScript code
Table of Content:
3 Places to put JavaScript code
- 1. Between the body tag of html
- 2 . Between the head tag of html
- 3. In .js file (external javaScript)
1. Code between the body tag
In the above example, we have displayed the dynamic content using JavaScript. Let’s see the simple example of JavaScript that displays alert dialog box.
2. Code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside the head tag.
In this example, we are creating a function msg(). To create function in JavaScript, you need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call msg() function.
Welcome to JavaScript
3. External JavaScript file
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files into a single file. It increases the speed of the webpage.
Let’s create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js
function msg(){ alert("Hello JavaScript"); }
Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.
index.html
Welcome to JavaScript
Advantages of External JavaScript
Placing scripts in external files has some advantages:
- It separates HTML and code
- It makes HTML and JavaScript easier to read and maintain
- Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags: