Inserting JavaScript
Now that we know what JavaScript is, lets learn the ways in which we can include JavaScript in our web page to make it dynamic.
You can add a JavaScript code in your webpage in three ways. We'll discuss them one by one.
Inserting JavaScript within body
We can put JavaScript code anywhere inside the body in our webpage using <script> tags. Here's simple structure how to include JavaScript in body. Generally we put script tags before closing body tag.
<!DOCTYPE html> <html> <head> <title>Inserting JavaScript</title> </head> <body> <p>This is an introduction to JavaScript</p> <script>alert("Hello JavaScript");</script> </body> </html>
Embedded JavaScript inside head tag
JavaScript code can be defined inside head of a web page using <script> tag. Have a close look at the code below.
<!DOCTYPE html> <html> <head> <title>JavaScript from Head</title> <script>alert("Hello JavaScript from head");</script> </head> <body> <p>This is an introduction to JavaScript</p> </body> </html>
Note : There is a difference between putting JavaScript in body and head. Since JavaScript code is interpreted line by line by the web browser, putting the code in head will execute the JavaScript code first and then any other HTML code. While putting it in body will execute the JavaScript code after rendering the HTML elements that comes before script tags. Keep this concept in mind.
External JavaScript
JavaScript code can be written in some external file and that file can be included in a web page using <script> tag. This is the preferred way of including a JavaScript code.
To see external JavaScript code in action, first create a simple HTML document and name it as 'test.htm'.
<!DOCTYPE html> <html> <head> <title>External JavaScript</title> <script type="text/javascript" src="external.js"></script> </head> <body> <p>This is an introduction to JavaScript</p> </body> </html>
Note the script tag inside head. Its actually pointing to an external JavaScript file (name 'external.js') using scr attribute of script tag. Now create this external file named 'external.js'.
alert("Hello from external JavaScript");