Like most
programming languages the default behaviour when JavaScript when runs is to
start at the first statement and move down executed each of them one by one.
This will happened when the browser sees your code. We can put the script tag
in <head> section, in <body> section in our html page or in the
middle. The best practise for most of the web designers is to add the script
tag just before the closing body tag.
Example:
<html>
<head>
<title>Untitled
Document</title>
</head>
<body>
<div
id="demo">
<h1>This is a
heading.</h1>
<p>This is a
paragraph.</p>
</div>
<script>
alert("This is a simple
alert.");
</script>
</body>
</html>
Now when we execute the above
code in browser the code will be executed line by line through the HTML and
when sees the script tag it will be executed after the HTML content, and that
what we want.
But if you add the script tag
inside the head section the code will first alert the JavaScript and then will
execute our html, and we don’t want that:
Example:
<html>
<head>
<title>Untitled
Document</title>
<script>
alert("This is a simple
alert.");
</script>
</head>
<body>
<div
id="demo">
<h1>This is a
heading.</h1>
<p>This is a
paragraph.</p>
</div>
</body>
</html>
The next question is where to
put JavaScript. Well, it’s not god practice to mix JavaScript with html because
it will be hard to edit and read. That’s because of this we use separate JavaScript
file in which you done need to add the script tag. Just type your JavaScript.
Here is an example how to add
external JavaScript file which have to be in the body section again.
Inside the
src=““attribute
add the path location of your script which must be with .js extension.
Example:
<html>
<head>
<title>Untitled
Document</title>
</head>
<body>
<div
id="demo">
<h1>This is a
heading.</h1>
<p>This is a
paragraph.</p>
</div>
<script
src="script.js"></script>
</body>
</html>
We suggest you to put stylesheets
and the top, the scripts at the bottom.
No comments:
Post a Comment