Today I learned

Organizing JavaScript for simple sites

This article was written in 2015, before Webpacker and React became mainstream. Much of this article refers to practices aimed towards Rails 4's asset pipeline.

Some sites don't need big JavaScript architectures, only bits of small behaviors that will affect certain elements. I prefer to put them into a directory called behaviors.

  • Each file is a self-contained piece of code that only affects a single element type.
  • Name each one of the files according to the class (or role) it affects.
  • They should also be independent of each other, and therefore, order-agnostic.

Example project

...
└── javascripts/
    └── behaviors/
        ├── colorpicker.js
        ├── modal.js
        ├── select2.js
        ├── tooltip.js
        └── wow.js
// select2.js -- affects `.select2`
$(function () {
  $('.select2').select2()
})
// wow.js -- affects `.wow`
$(function () {
  new WOW().init()
})
// tooltips.js -- affects `.tooltip`
$(document).on('hover', '.tooltip', function () {
  ...
});

Using behaviors

Just include them all into one file. In Rails, this should be as easy as:

//= require_tree ./behaviors

This JavaScript will be safe to include in all pages.

You have just read Organizing JavaScript for simple sites, written on February 26, 2015. This is Today I Learned, a collection of random tidbits I've learned through my day-to-day web development work. I'm Rico Sta. Cruz, @rstacruz on GitHub (and Twitter!).

← More articles