JavaScript wrangling has been among the most controversial topics in front-end development for a long time now. It’s right up there with tabs vs spaces and french press vs pour over. Here’s how we do at LexBlog in all current and foreseeable projects.

The Global Object

We kick off a plugin/theme JS file with a global that is namespaced for that project, containing handy functions used throughout.  Example:

In that example, you see the global object for our LXB MailChimp Tools plugin, written by myself and my teammate, Angelo Carosio. It only contains one helper function, for getting a value from a url query string. Almost as important as that helper function, is the fact that it declares (some would say, pollutes) `lxbMailChimpTools` as a variable in the global scope. I like this because, when done consistenty across themes/plugins, it serves as a handy way of identifying what code is running and what isn’t.

There will be jQuery

A lot of developers that I admire are pretty much done with jQuery.  I, sir, am not.  Three reasons:

  1. It’s a convenient syntax.
  2. If your project is on WordPress, it’s almost certainly going to be loading regardless of if you personally need it for your code.
  3. Browsers *gasp* still … have … bugs!

So, there will be jQuery, and it will be presented in the most consistent and organized fashion I can think of.  Peruse this example, where we implement tabbed panels, accordions, and sortable tables in our MailChimp plugin:

I’m omitting the function bodies for the sake of readability, but the point is we have three distinct features, each bundled as their own jQuery plugin. To put that differently, in all current and foreseeable LexBlog projects, there is a 1:1 relationship between user stories and jQuery plugins. It’s just an organized and scalable way to do it. We don’t stash a quick click event inline, or in the global scope. No matter how small the feature, it gets bundled into a jQuery plugin. That way it becomes very easy to manipulate when the code is executed, the elements to which it applies, or options that are passed in. The phrase, “The wider the base, the higher the peak” comes to mind.

2012 Called and they Want Their JS Boilerplate Methodology Back

When I first started web development, I was learning from a guy who used HTML tables for layouts, as I was reading about float-based layouts.  I was grateful for his help, but I found it difficult to avoid snickering about what he was doing, and what he was ignoring.  I absolutely get that this is not Angular, Node, Ember, Meteor, Famous, Backbone, React, Vue, MooTools, Prototype, or DHTML.  That’s kind of the point.  You will not find a JavaScript framework with a longer career than jQuery — and I’ll be delighted if it’s longer than my own career!