Rule #6: Declare global variables in the main web page.
All programmers must deal with lexical scope. If you are not experienced with that concept, you should find a resource that explains the concept in depth and then come back to this entry. If you're a programmer with little experience in web applications, the web page version of lexical scoping may be a little mystifying.
While programming a web page, always consider your global scope to be the same as the top-level of the web page's code, or document-level scope. In other words, the main web page file is your main() routine. Depending on your web server, there may be "areas" of the overall web application you could use as repositories of automatic, application-wide variables. Don't do this. You need to be explicit in your use of variables coming from outside a given web page file.
Scope is even more confusing in a web page because some of the code is parsed by the server, and the resulting HTML/JavaScript is parsed by the client web browser. You have two separate document-level scopes in a web page file that are essentially two independent programs tangled together.
Here's the checklist:
- Variables defined at the document-level, only for the current web page, should be defined explicitly in the main web page file.
- Any document-level variable derived from includes, a shared library, or an application-level variable should be explicitly called out. Don't bury it in a procedure without explanation.
- Explicitly put server-side variables into client-side variables for use in a JavaScript. Don't just write the server-side data into the body of a JavaScript.
- Variables should be offloaded to an include, shared library, or to application-level scope only for purposes of reuse.
The Simplest Example Possible
Let's say my web site has a standard-format header across my whole web application. It's output by the JavaScript function Header() kept in a shared library. Each individual page has unique global data, also stored in a shared businessHTML library. Header() needs to use this data on the client-side, to dynamically generate hyperlinks at the top of the page.
Following the tenets of this rule, as well as some of the other 10 rules, a snippet of my web page might look like this:
<?php require("scripts/templates.php"") ?>
<script type="text/javascript" src="scripts/templates.js"></script>
<script type="text/javascript">
var StrMeta = "`MetaForPage()`";
</script>
<body>
<script type="text/javascript"> Templates.Header()
</script>
<!-- some html here -->