Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Use Consistent Document Structure

Many times a script that applies to only a single page will be included with the HTML code instead of a separate file. By sticking to a consistent organizational structure within the code for the page as well, maintainability can be enhanced.

Group Embedded Script Code

We looked at a script example in a previous article, where the onclick event of the button was bound to the doCount() function. This script is reprinted in Listing 1. You can see by the trailing semicolon in the attribute value that this looks like JavaScript syntax. In fact, it is. The attribute is actually binding the code inside the quotes to the event—this code only coincidentally calls the doCount() function. So, it's possible to put code other than a function call in the attribute. For example, Listing 2 is functionally identical to Listing 1.

Listing 1: Binding a Client-Side Script to an Event

<html>
<head>
<title></title>
<script language="JavaScript">
 var nCount = 0;        // Executes when document loads
 alert("Count is " + nCount); // So does this

 function doCount() {
  alert(++nCount);      // Executes only when doCount is called
 }
</script>
</head>
<body>
 <input type="button" value="Increment" onclick="doCount();"> </body>
</html>

Listing 2: Placing Code in the Event Attribute

<html>
<head>
<title></title>
<script language="JavaScript">
 var nCount = 0;        // Executes when document loads
 alert("Count is " + nCount); // So does this
</script>
</head>
<body>
 <input type="button" value="Increment" onclick="alert(++nCount);">
</body>
</html>

While this is completely legal syntax, it is bad style. As much as possible, functional script code should be gathered together in one place for each of maintenance and reuse, not scattered throughout the document.

Position Within Head Tags Consistently

Script tags can appear anywhere in the HTML document, as long as they are defined (downloaded) before they are called. However, to simplify the task of finding and maintaining scripts in an HTML document, it's a good idea to group embedded scripts in the document head section either before or after style sheets and metatags. Use the same pattern in all source code files.

  • + Share This
  • 🔖 Save To Your Account