Serving

Selective imports

Pin a module without preloading it, then import it only on the pages that need it.

A page-specific module#

Write the module under app/javascript and pin it with preload: false, so it isn't fetched on every page:

app/javascript/checkout.js
// some checkout specific js
config/importmap.rb
# ... other pins ...
pin "checkout", preload: false

Importing it on one page#

Import the module on the specific page with javascript_import_module_tag. You'll likely want a content_for block on the page or partial, yielded in the layout:

app/views/checkouts/show.html.erb
<% content_for :head do %>
  <%= javascript_import_module_tag "checkout" %>
<% end %>
app/views/layouts/application.html.erb
<%= javascript_importmap_tags %>
<%= yield(:head) %>
javascript_import_module_tag must come after javascript_importmap_tags: the import map has to be in the document before any module that relies on it.