Open E-School

Male
Friday, February 24, 1984

Head or Body – Where to write your javascript code ?

Category: Programming Date: Thursday, March 26, 2015

Goal

Understand where in the HTML document you should write your javascript code

Role of the page <head> section

The <head> section in your HTML page is meant to write code which is more about the information about the page and the resources which you want to use in the page rather than the actual code which will help in the rendering of the page itself

Role of the <body> section

The <body> section in your HTML page is meant to write code which constructs your page in the browser. You write the entire HTML for creating the layout of your web page in the <body> section

What does javascript do?

You can use javascript for doing many things in your page, but the most important use which you can make of javascript is to manipulate the HTML elements in your page. For example you might want to turn some areas of the page visible and hide some other areas depending on your page logic. This is where you will be using javascript.

So where should you write your javascript code?

The answer to this question is very simple. You can write your javascript code anywhere you like in your page – either in the <head> section or in the <body> section. Still there are a few important things to consider before you can decide where to keep your javascript code

  1. If your javascript code will be used in your whole page then you should simply put it in the <head> section.
  2. HTML elements depending on javascript – If some of your page HTML elements will call the javascript functions on load then you should make sure that those javascript functions are placed before those elements in the page
  3. Javascript depending on HTML elements – If your javascript code depends on some html elements in the page then you should make sure that you write the javascript after those elements in the page.

To put it very simply you can put javascript in the page <head> or <body>, before or after any html element as long as the dependencies of your html elements and your javascript code are met properly.

Rate this article and help us improve

Please Login to rate
Overall ratings: 0 | Rating: out of 5
Previous Article Next Article

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp