Rails page specific asset bundles

This is my memo about page specific assets.

Single asset bundle vs multiple asset bundles

  • We can create a multiple asset bundles instead of default application.js.
  • Pros: Useful if some code is used only on certain occasions.
  • Cons: More http requests.

Page Specific Javascript

  • In a js file, we can conditionally execute code fragments based on attributes on body tag.
doctype html
html
  /...
  = content_tag :body, class: "#{action_name}_view", id: controller_name, data: { action: action_name, controller: controller_name } do
    /...
doctype html
html
  /...
  - body_class = user_signed_in? ? "body--logged-in" : "body"
  - body_data = { action: action_name.dasherize, controller: controller_path.parameterize.dasherize }
  = content_tag :body, class: body_class, data: body_data do
    /...

Resources