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");
<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>
</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>
<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.
Note : Javascript events reference
gud luck :)
No comments:
Post a Comment