There are two main places to keep your JavaScript code – On Page and External
On Page JavaScript
- You can write JavaScript on HTML pages anywhere between <html> and </html> tags.
- All on page JavaScript code must be inside <script> tag
- In script below, document.write is used to calculate the result of 5+6.
- A semicolon ; represents of end of statement in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> <script> document.write(5 + 6); </script> </head> <body> <any>content</any> <any>content</any> <any>content</any> </body> </html> |
External JavaScript
- You can write all your JavaScript code in an external file and then link that file to any of your HTML pages.
- External JavaScript files use a .js extension, for example, myfile.js or external-javascript.js
- To use an external JavaScript file, use the <script> tag with src attribute, followed by the path to your external javascript file.
- You can include resources in the head tag but now a days it is recommended to place JavaScript just before closing Body Tag.
- You can include script at the end of document.
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> <script type="text/javascript" src="path/to/RESOURCE.js"></script> <script type="text/javascript" src="path/to/LIBRARY.js"></script> <script type="text/javascript" src="path/to/PLUGIN.js"></script> </head> <body> <any>content</any> <any>content</any> <any>content</any> <script type="text/javascript" src="path/to/SCRIPT.js"></script> </body></html> |