- Use include files.
- Use a consistent document structure.
- Write granular, generic functions.
- Bind functions to events.
Use Include Files
Organizing client-side script code into files separate from the HTML code offers a number of benefits. First, maintenance is simplified when code is concentrated in only a few files. This is especially useful when functions change frequently or when they depend on hard-coded data constants. Also, the use of external script files promotes code reuse by organizing functions into libraries of routines that can be easily leveraged across the Web application and in applications across the enterprise. Finally, the Web browser caches separate script files on the client. Then, when other pages refer to the same script file, the browser loads it from the cache instead of downloading it again from the server, resulting in better performance.
Using scripts stored in an external file couldn't be easier. As the following code illustrates, it is simply a matter of adding the src attribute and value to the <script> tag:
When the browser encounters this tag, it will look in the client-side cache for a file that matches the fully qualified URL specified in the value of the src attribute. If this is not found in the cache, it is downloaded from the server.
Following a few rules about structuring the Web application will help you get the most out of external script files. First, prefer relative pathnames, as shown in the previous code, to absolute pathnames, as in the value of the src attribute:
Sticking to relative pathnames will aid in the deployment and maintenance of the site. Because the code does not assume a given folder structure, it will be easier to make changes to the topology of the Web application as well as to use the library of script code in other applications.
Another common mistake is to group too many functions together in a single include file. Often, this is based on some artificial categorization. For example, some developers place all "utility" functions in a single include file. Such a file might contain functions as disparate as math calculations, character case conversion, and data validation.
This becomes a problem only when the script file contains many more functions than are actually required. If a large amount of code is included from an external file on the server, the entire file must be read in and sent to the client, even if only a little of it is used. Also, including more code in a script file than needed results in the unnecessary exposure of intellectual property because users can easily inspect client-side code. It's a better strategy to organize the code into script files that are relatively granular, trying to strike a balance between maintainability and performance.