↑
Main Page
Tag placement
?
Code Maintenance
— If JavaScript code is sprinkled throughout various pages, code maintenance
becomes a nightmare. It is much easier to have a directory for all JavaScript files so that when a
JavaScript error occurs, there is no question about where the code is located.
?
Caching
— Browsers cache all externally linked JavaScript files according to specific settings,
meaning that if two pages are using the same file, it is only downloaded once. This ultimately
means faster loading times. Including the same code in multiple pages is not only wasteful, but
also increases the page size and thus increases the download time.
Tag placement
Generally speaking, it is common to place all code and function definitions in the
<head/>
tag of an
HTML page so that the code is fully loaded and ready for use once the body is rendered. The only code
that should appear within the
<body/>
tag is code that calls the functions defined previously.
When the
<script/>
tag is placed inside of the
<body/>
tag, the script is executed as soon as that part
of the page is downloaded to the browser. This makes it possible to execute JavaScript code before the
entire page is loaded. For example:
<html>
<head>
<title>Title of Page</title>
<script language=”JavaScript”>
function sayHi() {
alert(“Hi”);
}
</script>
</head>
<body>
<script language=”JavaScript”>
sayHi();
</script>
<p>This is the first text the user will see.</p>
</body>
</html>
In this code, the
sayHi()
method is called before any text is displayed on the page, meaning that the
alert pops up before the text “This is the first text the user will see.” is ever rendered. This method of
calling JavaScript inside the
<body/>
of a page is not recommended and should be avoided whenever
possible. Instead, it is recommended to use JavaScript only as an
event handler
in the body of a page,
such as:
<html>
<head>
<title>Title of Page</title>
<script language=”JavaScript”>
function sayHi() {
alert(“Hi”);
}
</script>
</head>
<body>
128
Chapter 5
08_579088 ch05.qxd 3/28/05 11:37 AM Page 128
Free JavaScript Editor
Ajax Editor
©
→