Skip to content

Style Guide: JavaScript

Matt Budz edited this page Dec 5, 2023 · 2 revisions

Architecture

All JavaScript files are located in app/assets/javascripts/.

Scripts are further divided by layout and located in the respective layout's folder. For example: app/assets/javascripts/tylium

Within the layout folder you will typically see 2 folders and 2 files:

  • /pages
    • This directory contains scripts specific to a single view.
  • /vendor
    • This directory contains any JS files not written by us, such as Bootstrap, jQuery, etc.
  • behaviors.js
    • This script contains code that is used across multiple views.
  • theme.js
    • This is the javascript manifest that is referenced in HTML and references all scripts used in the layout.

Note: If the script is shared by multiple layouts (ie: Tylium, Application, and/or Setup, etc.) the stylesheet is located in: app/assets/javascripts/shared

Code

  • By default, we do not add JS dependencies. We don't want to rely on 3rd party code which may in turn have its own additional dependencies. 3rd party libraries may get abandoned or end up unmaintained for years resulting in incompatibility with our code base. Not to mention, some libraries are very robust resulting in a boated JS bundle when we only need a subset of features. Having said that, if there is a strong case for adding a JS dependency, pitch it, and we'll collectively decide the appropriate way forward.
  • Select elements using data-attributes not class names, element types, or id's. If you are working on a script and notice it is depending on CSS class names, element id's, etc, convert the script to use data-attributes.
  • Use Vanilla JS (optionally with jQuery), do not use CoffeeScript. When working on a script that currently uses CoffeeScript, submit a separate PR to convert CoffeeScript to Vanilla JS. This makes reviewing the code easier rather than translating and editing/adding code in one PR. Once this CS->JS translation PR is merged to develop, update the feature branch by merging the develop branch into the feature branch and add in the new vanilla JS.
  • Use descriptive comments when adding in new code that is obscure.
  • Do not use inline onchange attributes (or similar)
  • Use turbolinks:load event listeners instead of DOMContentLoaded, window.onload, jQuery ready etc.
document.addEventListener("turbolinks:load", function(){
  // do things
})

More about Turbolinks here

Clone this wiki locally