Skip to content

Instantly share code, notes, and snippets.

@BLaurenB
Created June 25, 2021 14:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BLaurenB/5bcb126af5e948beba153ce31ad4cfc0 to your computer and use it in GitHub Desktop.
Save BLaurenB/5bcb126af5e948beba153ce31ad4cfc0 to your computer and use it in GitHub Desktop.

Lazy Loading with HOTwire in Rails Views

If you boil it all down, here is the basic flow through an app, for a single lazy-loaded piece of content. (The whole flow would be repeated for any other piece of lazy loaded content in the app.)

  1. A section of an existing view has a turbo_frame_tag wrapping a piece of place-holding text or functionality (like a spinner or some text). The options passed to the tag include an id and a src. The src is a url for a controller method.
  2. There is a view that contains the 'real' content that will replace the placeholder content. It's not a partial. This is because it must correspond to a controller method of the same name. The whole content in this view is wrapped in a turbo_frame_tag, and the id must match the id in the placeholder tag. There should not be a src declared in this tag. The view, of course, could simply call an existing partial from within the turbo_frame_tag.
  3. The url declared in the src is a route and a controller method that correspond to the view name. The method defines any instance vars that are needed for this view.
  4. When the initial page is loaded, and the browser hits the turbo_frame_tag with the placeholder content, it sees the src and sends a request to that controller method. The controller receives the request, does any work defined in the corresponding method, and then sends instance vars (if any) to the View. The view is rendered on the existing page in the space that was set up by the placeholder turbo-frame-tag by finding the corresponding id. The user only sees that the initial page has loaded, and that a section of the page has new content that wasn't there initially.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment