Monday, May 18, 2009

Difference between Javascript in head and body section

Hi folks, I had very little knowledge in Javascript. So far, I have been stealing the scripts from some Javascript sites & blogs and ofcourse, google helped me a lot ;). Felt little asahmed to search for simple and basic Javascripts. So, started reading JS from scratch. Better late than never :)

Alright, this is a most basic concept that I read. This post might looks silly and funny for JS gurus. But, it is valuable piece of information for a newbie like me. 

JS is a sequence of statements to be executed by the browser. It can be embedded both in <head> and <body> sections of the HTML document. Sometime, this puts us in dilemma and can be solved by knowing the difference between embedding them in the above sections. 

JS in <head> Section :
      Scripts in this section will be executed when called, or when an event is triggered. This will ensure that the script is loaded before anyone uses it.

Example:

<html>
   <head>
      <script type="text/javascript">
         function message()
           {
               alert(This message is defined in head section and called with onload event");
           }
      </script
>
   </head>

   <body onload="message()">
   </body>
</html>


JS in <body> Section :
     Scripts in this section will be executed while the page loads. 

Example:

<html>
   <head>  </head>
   <body>
      <script type="text/javascript">
         document.write("This message is displayed on page load");
      </script
>
   </body>
</html
>
   
The above written JS is page specific. If you want to use the same script in multiple pages, save it as a Javascript file(.js) and include in the <head> section using <script> tag.


gud luck :)

No comments: