Disclaimer: I speak in absolutes below for brevity. Yes, nearly every “rule” in programming has exceptions.
JavaScript is hard. It moves so fast that it’s often unclear whether you’re “doing it wrong” at any given moment. Some days it feels like the bad parts outweigh the good parts.
Yet there’s no point in fighting it. JavaScript is eating the world. So we might as well do it right.
Here’s my take.
1. JS Belongs in a .js File
“C’mon, it’s only a few lines…” Yes, I mean nearly all. Why? Because it aids readability, enforces structure, and saves bandwidth. Inline JavaScript must be downloaded every time the page is loaded. In contrast, separate .js files are cached. As you’ll see, this rule helps support a long list of other rules below. That’s why it’s rule #1.
2. JS Code Should be Static
I’ve seen many creative hacks for making JavaScript dynamic. People use server-side languages like C#, Ruby, or Java to write dynamic JavaScript in a string. Don’t do that. You lose code coloring, syntax highlighting, and intellisense support. And remember, JavaScript belongs in a .js file (see rule #1).
Instead, use JSON to introduce dynamic behavior. I call this the JavaScript Configuration Object Pattern. Here’s how: inject JSON into the head of your application and utilize that data to fork logic as needed. You might be thinking “Hey, this contradicts rule 1!” I view JSON as data, not code, so I make an exception here in order to support static, separate JavaScript files.
StackOverflow uses this pattern. As does Google. So you’re in good company. Just view their source:
As you can see, StackOverflow is injecting personal settings like isNoticesTabEnabled. This simple snippet of JSON provides the necessary data for providing custom behaviors while using static JavaScript code files. To make this happen, serialize a server-side class into JSON and place the result in
. Then you can reference this data structure as needed in your static JavaScript code, knowing it will be available because it’s injected in the <head>.
I always want to know what the latest frameworks are, but its a good reminder to always get the fundamentals down first. Good article.