Chapter: Exploring the examples on htmx.org
Lecture: Example: Lazy loading
0:00 The next example that we're gonna explore. It's not one that actually appears in our final application, but it's extremely useful.
0:07 Let me lay out the scenario for you. Imagine I've got a page, trying to render it for the user, right? They make a request, we want to show it to him,
0:15 but maybe it's doing some kind of report, or there is some part of the page that's actually really,
0:19 really slow, and I want to get most of the page shown to them and then
0:23 have this other slower section, like a report or a graph or something along those
0:27 lines. I want that to be generated and delivered to the user as soon as
0:32 possible, but without blocking the original page load, and we also want some kind of indicator
0:36 for what's happening. That would fall under the "Lazy Loading" section. Check this out, that's pretty simple.
0:42 So what we do is we say, this section of the page, this whole section, that's one of those slow pieces.
0:48 What I want to do is I want you htmx, to go to the server and call /graph and when it's done, put it right here.
0:56 But while it's loading, I want you to show this indicator with those bars sort
1:01 of spinning around here. And the trigger is going to be that the page has loaded.
1:05 So just the page was shown and then fill out these missing pieces that are slow. In order for this to work,
1:12 you're going to need a little bit of CSS somewhere, included in the page to basically
1:17 have some of the behaviors that are indicated here happening and down here we have our
1:22 graph and this is the part that was slow, but it doesn't take that long, it's like half a second or a second.
1:28 So what we didn't see is this actually loading because by the time I got down here it was done. But if, notice if I load this page, it's instant,
1:35 but there's like a one second processing of something else. If I scroll down, I can refresh here and show that to you.
1:42 So page is loaded. But now it's thinking on the graph request, input came back or the response came back. Boom,
1:49 here's our report and let's go and look at this. So our initial state was that the page was loaded and this section was here.
1:57 Right, this is what we talked about. But then as the document loaded, was complete,
2:03 I said right, now we've got to fill out the slow pieces, and it went and did a request for GET /graph,
2:08 no parameters. The response was, here is your generated image, of your report. How cool is that? So I'm
2:16 sure there are many websites that there's a little part of it or a little
2:19 piece of information that's slow and the rest is really pretty quick, and yet the user
2:24 experiences, I go there and I click, and I wait, and I wait, and I wait and finally the page loads.
2:30 This would be so much better. Show most of the page, and calculate the little final things that you need using one of these lazy loads.