@samnang, is you’re using a CDN to cache your JS or at least putting TTL on the assets so that they aren’t being downloaded over and over again for each page, there isn’t much penalty to sending one large JS file everywhere. Sending the same large JS file everywhere is likely preferable to sending 20 different JS files depending on the page.
A second benefit of the JS monolith is that it’s easier to maintain. You don’t have bugs where one page expects some JS that might not be there because you forgot which files went where.
At our company, we do have two JS payloads. Marketing pages, which are delivered to unauthenticated users, are much slimmer and only contain the bare minimum JS that we need to show our homepage, contact form, and marketing copy. I put all of this code into
foundation.coffee, and then declare it as an asset to precompile in
application.rb. We then have a much larger file,
application.coffee that first includes the foundation file at the top using Sprockets’
require= directive, and then loads all the JS that is only relevant to application users: libraries like React that powers our UI, and all the behavioral code that governs the application.
We get the benefit of the marketing-only JS file loading very quickly, which I think is important to potential clients who are visiting your site. You want to look clean, fast, and snappy. That being said, while I’m happy with our two-payload approach, I would not want to go further than that in terms of dividing into page-specific payloads.
content_for method, but I try to avoid that as much as possible since it involves putting JS/Coffeescript code into Rails templates, and is an un-ideal way to organize logic (and separate code form like languages into like folders).
Another way to split js/css assets is based on how frequently they change. So for example you could bundle all your vendor assets in one file, and your main application assets in another. That way the large vendor assets can stay cached longer, while the smaller app assets get cache busted frequently.