DEV Community


Posted on

Shrink your Rails 7 application.js files

I discovered that my rails app was bundling a few too many stimulus controllers. Whoa! Slow down there buddy, save some of those controllers for individual pages! Here's my browser trying to download the deferred file...

Maybe you're like me and you thought... "you can choose which stimulus controllers to import?"

Yes. Obvs.

I followed the upgrade tutorials and my application.js using esbuild and js-bundling_rails loaded my new stimulus controllers like this:

import '@hotwired/turbo-rails';
import './controllers';
Enter fullscreen mode Exit fullscreen mode

I added a few more controllers and then BAM! I had a massive 4.5MB application.js file!

Turns out I had a couple pages that used a third party UI component and for reasons I couldn't stop using those components. So I loaded them into my controllers.

I didn't want to stop using the controllers in the same way, but I wanted to use them when I needed them. So I load my controllers dynamically now. But I still register them to the { Application }

Here is my current setup:

Image description

Anything in my controllers directory goes to application.js. I use active admin...(I know, I know, zip it.)

So I load jquery to the window when I'm on active admin pages.

I then bring in my other controllers individually and use `<%= javascript_include_tag 'preview(or upload)' %> where needed.

Here's what the preview directory looks like:

Image description

Here is what the index.js file looks like.

import { application } from "../controllers/application"

import PreviewController from "./preview_controller"
application.register("preview", PreviewController)

So now my application.js file is 13x smaller. Maybe there is a better way to do it. I'm not entirely sure. But here I am putting out a way where it works for me. Lighthouse Performance score went from 33 to 93. I really don't need that much javascript globally so I'll be trying to deliver almost 0 javascript to the page over time. I'll have ChatGPT research the best admin, or roll my own for me 😂.

Top comments (2)

konnorrogers profile image
Konnor Rogers

There’s an infinite number of ways to handle this with some techniques more advanced than others including lazy loading controllers based on controllers found in the DOM.

An easy win you could do is setup ESBuild to take in multiple entrypoints and set format to “ESM” and “splitting” to true so you can get a more granular cache and reuse code from your main application in your admin views.

lucianghinda profile image
Lucian Ghinda

If you are looking for an alternative to active admin may I recommend ?