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:

  1. The header of the page in between 'head' tags.
  2. Body of the page in between 'body' tags.
  3. In an external file with .js extension.

Placing Javascript between 'head' tags

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.

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.


Content of scriptfile.js

Content of html file

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).
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About