...

/

Embrace Plain JavasScript for Basic Interactions

Embrace Plain JavasScript for Basic Interactions

Learn how plain Javascript is used for basic interactions in Rails.

Overview

Despite the above-average carrying cost of JavaScript in our app, we cannot avoid it, and many features of our app will require some JavaScript. We don’t want to stubbornly avoid JavaScript at all costs, but we do want to carefully manage how we use it.

We’ll discuss three techniques to maintain control over our JavaScript, but keep in mind these are only scratching the surface. The more JavaScript we have, the more closely we’ll need to manage it—the same as any code in our app.

The three techniques we’ll discuss here are:

  • Embrace plain JavaScript for basic interactions wherever we can.
  • Use one framework at most, like Hotwire or React, and choose that framework for sustainability.
  • Ensure our system tests break when our JavaScript is broken.

Let’s jump into the first technique, which is to embrace the power of plain, framework-free JavaScript.

JavaScript for basic interactions

The more dependencies our app has, the harder it’s going to be to maintain. Fixing bugs, addressing security issues, and leveraging new features all require updating and managing our dependencies. Further, as we discussed previously, the fewer ways of doing something in the app, the better.

Our app likely doesn’t need many interactive features, especially when it’s young. For any interactivity that we do need, it can often be simpler to build features that work without JavaScript and then add interactivity on top of that. Modern browsers provide powerful APIs for interacting with our markup, and it can reduce the overall complexity of our app to use those APIs before reaching for something like React.

Let’s do that in this section. Our existing widget rating system is built in a classic fashion. Although there is no back-end currently, we might imagine that it will show our rating for any widget where we’ve provided one. Let’s suppose we want to do that without a page refresh. We want the user to submit a rating and have the page remove the widget rating form and replace it with a message like “You rated this widget 4.”

Let’s see how to do this with just plain JavaScript. The recently-introduced ...