{ Modular jQuery }

jQuery, while still extremely popular due to its ease of use for small projects, can quickly turn into “spaghetti code” when scaling. About ten years ago, it was the greatest thing since sliced bread for me, as I wasn’t all that familiar with JavaScript yet and it was easy to learn. Since the advent of ES6 / ES2015 I’ve scrapped it from my projects altogether, except for some dev dependencies require it for them to work. I’ve found this site to be a nifty quick reference tool – http://youmightnotneedjquery.com/ for those wishing to make the switch to modern JS.

One of the main things that still make it popular today is that it makes cross-browser compliance easy to accomplish. The differences between browser rendering engines are already taken care of for you in many instances. Especially during the “browser wars” era, where Internet Explorer, amongst others, forced you to implement tasks like event handling completely differently.

When using jQuery, I’ve found the module based approach to be the most logical and performant. As an example, we start off with a root module – lets call it Helper.

We kick off our module and define just the one global variable called helper which is assigned to our closure or IIFE (immediately invoked function expression) depending on how you’ve learned it. We create one private method – initModule and a couple of utility functions.

Then we create the shell, which is there to kick off other modules and serve as a .. well.. shell for the rest of the modules to communicate with.

We make sure to setup the initModule method, which we call in the root namespace, which in turn receives a $container argument. We pass it the root element, and use setJqueryMap() to effectively cache elements so we don’t end up creating multiple jQuery instances by calling $() each time we need to reference one.

The full version of this script has a lot of selectors, this is kept brief to illustrate the methodology. Assuming we’re in the old school “add a bunch of script tags” era, we’d include the scripts like this at the end of the document:

<script src="scripts/helper.js"></script>
// other module(s) that are invoked by helper
<script src="scripts/helper.shell.js"></script>
<script>
    (function() {
        helper.initModule($("body")); // or any DOM element
    })();
</script>

More to come on this.