Where to write Javascript code?
There is a flexibility given to include JavaScript code anywhere in an HTML document. Javascript code can be embedded in:- The header of the page in between 'head' tags.
- Body of the page in between 'body' tags.
- In an external file with .js extension.
Placing Javascript between 'head' tags
<!DOCTYPE html>
<html>
<head>
<script>
alert("JavaScript run from HTML Head tag");
</script>
</head>
<body>
Your html content here
</body>
</html>
Anything in the html head must be completed before the body is loaded, so it is generally a bad idea to put javascript in there. If you need something while the body is loading, or want to expedite some ajax, then it would be appropriate to put it in the head .
Placing Javascript between 'body' tags
JavaScript programs can be inserted inside the html body with the help of the < script > < /script > tag.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
alert("JavaScript run from HTML Body tag");
</script>
</body>
</html>
JavaScript from External script File
JavaScript code can either be embedded in your HTML files (above examples) or placed in an external script file with a .js extension. 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. When you place your JavaScript in an external file, put the name of the script file (.js) in the source (src) attribute of the < script > element.
<script src="sriptfile.js">....</script>
example
Content of scriptfile.js
function message(){
alert("Run from script file!!");
}
Content of html file
<html>
<head>
<script type="text/javascript" src="scriptfile.js"></script>
</head>
<body>
<p>Run JavaScript from script file</p>
<form>
<input type="button" value="click" onclick="message()"/>
</form>
</body>
</html>
The biggest advantage of external Javascript files are code reuse. If your Javascript is used by more than one page you do not need to repeat the script in each page that uses it. Moreover, if you want to update your script you need only change it in one place.
Current recommendations are to place the javascript at the bottom not because it "looks like it loads faster", but because by placing them there, javascript parsing and execution doesn't stop the browser from doing other things (like loading the rest of the page).
Related Topics