skip to content

With Turbo Frames in Rails 8.1, how do src and loading="lazy" defer part of a page, and what does turbo_frame_request? change on the server?

level: middleimportance: should knowfreq 45%

answer

  1. src loads after the page
  2. eager by default, lazy on visibility
  3. Turbo-Frame request header
  4. minimal turbo_rails/frame layout
  5. reload() re-fetches from src

basics

~20 s

A <turbo-frame> with src fetches that URL after the page renders, at once by default or when it scrolls into view with loading="lazy". turbo_frame_request? tells Rails the request came from a frame, and turbo-rails then renders a minimal layout.

solid answer

~50 s

A frame with a `src` loads its content in a separate request once it is on the page. `loading` is `eager` by default, so the request starts immediately; `loading="lazy"` waits until the frame enters the viewport, which suits trays, tabs and content below the fold. Any content written inside the frame shows until the response arrives, so a placeholder or spinner goes there. The response must contain a `<turbo-frame>` with the same id; the responding frame needs no `src` of its own. Turbo sends the `Turbo-Frame` header with the frame's id, and turbo-rails' `turbo_frame_request?` is true when it is present. turbo-rails then renders the minimal `turbo_rails/frame` layout instead of the application layout and varies the ETag, so frame and full-page responses are never cached as each other. `frame.reload()` fetches the frame again from its current `src`.

code

erb · 9 lines
erb
<%# app/views/contacts/show.html.erb %>
<%= turbo_frame_tag "recent_activity", src: activity_contact_path(@contact), loading: "lazy" do %>
  <p>Loading recent activity...</p>
<% end %>

<%# app/views/contacts/activity.html.erb %>
<%= turbo_frame_tag "recent_activity" do %>
  <%= render @contact.activities %>
<% end %>

go deeper

for a junior

Know that a turbo-frame with src loads its content in its own request, and that loading="lazy" waits until the frame is visible.

for a middle

Explain the Turbo-Frame header, turbo_frame_request?, the minimal turbo_rails/frame layout and ETag variation, and how reload() and setting src navigate a frame.

for a senior

Decide which regions to defer for render speed or cache reuse, avoid one-request-per-row designs, and handle redirects that land a frame on a page without its id.

for a principal

Use deferred frames to split pages by audience and change rate, so shared content caches for everyone while personal regions load on their own.

## Deferring a region with src A `<turbo-frame>` that carries a `src` attribute is filled by its own HTTP request rather than by the page that contains it. In a Rails view: ```erb <%= turbo_frame_tag "recent_activity", src: activity_contacts_path, loading: "lazy" do %> <p>Loading recent activity...</p> <% end %> ``` `turbo_frame_tag` passes `src` through `url_for`, so a route helper or a record works. The page renders first; the frame then fetches its URL and swaps in the matching frame from the response. The placeholder inside the block stays visible until then. The responding view wraps its content in a frame with the **same id** and **no `src`**: the attribute belongs only on the frame that needs to load. ## Eager versus lazy | `loading` | When the request starts | Typical use | |---|---|---| | `eager` (default) | as soon as the frame is connected to the page | content needed right away but slow to compute | | `lazy` | when the frame enters the viewport (an `IntersectionObserver`) | collapsed `<details>`, hidden tabs, content below the fold, modals | While the request runs Turbo sets `busy` and `aria-busy="true"` on the frame, and removes them when it finishes; after a navigation it sets `complete`. CSS such as `turbo-frame[busy]` can dim a loading frame. The element also has a `disabled` attribute that stops it from navigating at all. Why defer at all? The Turbo handbook gives two reasons: - **Speed of the first render.** An expensive panel no longer holds up the whole page. - **Cache dynamics.** A page that mixes content shared by everyone with per-user content is hard to fragment-cache. Moving the personal part into a frame lets the rest be cached for all users, or the reverse. Each eager frame is still another request, and frames that pop in above the fold cause layout jitter, so they are best reserved for content that is slow, personal or not immediately visible. ## What the server sees: turbo_frame_request? Every request a frame makes carries the header `Turbo-Frame` with the frame's id. turbo-rails includes `Turbo::Frames::FrameRequest` in `ActionController::Base`, which adds: - `turbo_frame_request?`, true when that header is present, available in controllers and views; - `turbo_frame_request_id`, the header's value; - `layout -> { "turbo_rails/frame" if turbo_frame_request? }`, a minimal layout that renders `csrf_meta_tags`, `yield :head` and the body, skipping the application layout's assets and navigation; - `etag { :frame if turbo_frame_request? }`, so a frame response and a full-page response for the same URL get different ETags. This is purely an optimisation. Turbo extracts the matching frame either way, so a full layout would also work. An app can override the minimal layout by adding `app/views/layouts/turbo_rails/frame.html.erb`; a controller that declares its own `layout` replaces the lambda and renders its layout for frame requests too. Controllers occasionally branch on `turbo_frame_request?`, for example to skip work only the full page needs. Use it sparingly: the same URL should keep working as a full page when opened in a new tab. ## Reloading a frame `FrameElement.reload()` re-fetches the frame from its current `src` and returns a Promise that resolves when the new content has loaded. After a frame navigation Turbo updates `src` to the URL it loaded, so `reload()` refreshes whatever the frame shows now. A Stimulus controller can call it after an action elsewhere on the page changes the frame's data: ```javascript document.getElementById("recent_activity").reload() ``` Setting `src` to a new URL from JavaScript also navigates the frame, eagerly or, for a lazy frame, when it next becomes visible. ## Pitfalls 1. **Missing frame in the response.** If the `src` action renders without a frame of the same id, the frame shows "Content missing" and fires `turbo:frame-missing`. 2. **Authentication redirects.** A lazy frame whose request is redirected to a login page receives a page without the frame; that case needs `turbo-visit-control` or a `turbo:frame-missing` handler. 3. **N frames, N requests.** A list that gives every row its own eager `src` frame turns one page view into many requests; lazy loading or a single frame around the list is cheaper.

  • Why does turbo-rails change the ETag for frame requests?
    A frame request is rendered with the minimal `turbo_rails/frame` layout, so its body differs from the full page at the same URL. Adding `:frame` to the ETag keeps a conditional GET from serving one version for the other.
  • How do you refresh a lazily loaded frame after the user changes data elsewhere on the page?
    Call `reload()` on the `<turbo-frame>` element, for example from a Stimulus action. It clears `complete`, re-fetches from the frame's current `src` and returns a Promise that resolves when the new content has rendered.

  • A lazy frame starts loading as soon as the page finishes rendering.
  • The responding view must also put src on its turbo-frame tag.
  • turbo_frame_request? checks request.xhr?, the X-Requested-With header.
  • Without the minimal frame layout, frame requests would not work at all.
  • frame.reload() re-renders the frame from the page's snapshot cache.
  • Frame requests skip the controller's before_action callbacks.