🖱 Infinite Scrolling Feeds in Svelte #
Let’s look at SvelteKit infinite scroll. The Instagram app itself is the perfect example of an infinite scrolling feed. There are potentially many posts available, and the app does not load them all initially; doing so would slow the page down, impacting user experience. Instead, it loads a few posts and as the user scrolls down, it starts lazy loading more posts. Lazy loading is just a way of saying we load content on demand (or, ideally, when we anticipate demand).
We will implement infinite scroll on a SvelteKit app, using images from your Instagram feed. In doing so, we need a trigger for automatically loading more content. For this, we can use the Intersection Observer API. When the user scrolls down and the footer becomes visible, we will get an observe event and load more content (where there are more posts available). As well as Intersection Observer, from the Svelte toolkit, we will be using a reactive function and stores.
We focus on an Instagram application for infinite scrolling in this article. However, it is not too much effort to apply the techniques here to a blog roll on your site, feeds from other social sites like Twitter or for user interactions on a social app you are building. If that sounds like something you might find useful, then why don’t we get cracking?
🔑 Instagram Access Token #
We will focus on the SvelteKit side in the post, so that it doesn’t get too long. If you want to code along, you will need an Instagram access token. There are currently two Instagram APIs. Here we just want to get images from a particular user’s feed, and the Instagram Basic Display API matches ours needs. Follow Facebook’s Get Started with Instagram Basic Display API to get your access token.
You will see, as part of the tutorial, you will set up a test user. Use your own Instagram account (or at least the one you want to extract the feed from). Select the Media (optional) box to be able to pull the feed images in, when asked to authorize your account. Once you have an access token, you can move on to setting up the SvelteKit app.
A temporary access token is fine for a proof of concept, though if you want to pursue the product to production you will eventually need longer living tokens.
⚙️ Svelte Setup #
We’ll create a skeleton SvelteKit project and put this thing together from there. To get going, type these commands in the terminal:
Select a skeleton project, answer no to Typescript and yes to both Prettier and ESLint. Let’s create an environment variable file next:
Then finally spin up a dev server:
🧱 SvelteKit Infinite Scroll: API Routes #
Next we’ll build a couple of server routes. We will use these to query the Instagram API
from the client. First, create src/routes/+page.server
. Add the
following content:
This code gets called automatically when we load the home page, and we can access the data
which we return here from the home page Svelte file. That data is just return the response the server
receives from Instagram, (if all is well)! That response will be JSON and something like this:
There will be up to 25 posts (I just included two here). Note the paging
object includes a next
link. We will use this when we need to download
more images. Let’s code up the endpoint for that next.
Pulling more Images from Instagram API #
To get more images, we just need the next
link included in the previous
call. Create a server endpoint for pulling more images at src/routes/api/instagram-feed-more.json/+server.js
and add this content:
We will access this endpoint using the POST
method and include the
next
link in the API call body.
With our API routes now all set up, let’s add one more piece of plumbing before we code up the client page.
🛍 Svelte Store #
Initially, we will show six images, though we would have pulled up to 25 in the first API call.
The store helps us out here. We put all the images we pulled from Instagram into the store and
then (initially) show the first six. As the user scrolls down, we will load more images from the
store. Eventually, it’s possible the user will want more images than there are available in
the store. At that point, we make a more
Instagram call, returning
up to 25 more images. We append those new images onto the end of what’s in the store already
and we’re away!
That probably sounded more complicated than Svelte actually makes it, but I wanted to run through
the logic before we implement it. As it happens, we only need three lines of JavaScript to set
this store up in SvelteKit! Create a file at src/lib/shared/store/instagram.js
(you will need to create some folders). Add these lines to the file:
In line 3
, we are initializing the store to an empty array.
Let’s add something now from the client.
🧑🏽 Client Side #
As we mentioned earlier, we can access the data we pull from the Instagram API in the src/routes/+page.server.js
server route in the Svelte markup We do that next. Replace the content in src/routes/+page.svelte
:
We have the feed posts available in the data prop, which we import (Svelte syntax is to use the export
keyword here) in line 9
. We destructure the feed and then
adding the data to the store is simply done in line 15
with instagram.set(feed)
. Could there be less boilerplate? 😅
I should mention, we imported the store in line 2
. In line 20
you see an example of how we can access the store. We just write $instagram
and that gives us the array which we set the store to be. In this line, we check how many elements
are currently in the store array.
Intersection Observer #
Okay, next we want to be able to show more posts (if we have them) whenever the footer comes into
view. The Intersection Observer API is our friend here. If this is your first time using it in
Svelte, check out the post on tracking page views, where we look at Intersection Observer in more detail. Add this code to the bottom of src/routes/+page.svelte
:
We will set the minimum page height so that the footer is initially out of view (in styles which
we add in a moment). Our Intersection Observer parameters will observe an intersection event when
the user scrolls down and the footer becomes visible. This will call the showMorePosts
function. To help here, we will bind the footer
variable (in line 25
) to the actual rendered footer element.
showMorePosts
is declared as a reactive function (in line 41
). This is a hint to the Svelte compiler that the function changes some elements in the DOM and
a refresh might be needed when it is finished.
In line 56
, we just make sure we replace URL encoded commas in the next
string with actual commas. Let me know if anything here could do with more explanation, and I can
update the post. Let’s actually render the content next.
Client Rendered Markup #
Paste this code at the bottom of src/routes/+page.svelte
:
There are a few things worth mentioning here:
-
in line
80
we just take the number of posts we want from the store, rather than the whole thing, -
we use
bind:this
to attach the footer element to the variable we mentioned before, used above by the Intersection Observer code, - I’ve just included the footer content in the example for the sake of the Intersection Observer code.
SvelteKit Infinite Scroll: Styling #
Here’s some (mostly) optional styling, just paste it at the bottom of our file. Be sure at
least to set the min-height
as in line 127
:
src/routes/index.svelte
— click to expand code.
🗳 Poll #
💯 SvelteKit Infinite Scroll: Testing #
That’s it. Give your browser a refresh and get scrolling! If your internet connection is fast, you might not notice more images loading. Keen an eye on the vertical scroll bar, though, and you will see it jumps as more content (off-screen) loads.
🙌🏽 SvelteKit Infinite Scroll: What we Learned #
In this post, we learned:
- using the Instagram API to fetch a user’s posts;
- how you can use store in Svelte to buffer content received from an external feed; and
- combining the Intersection Observer API with Svelte stores for a seamless user experience.
I do hope there is at least one thing in this article which you can use in your work or a side project. For extensions, you could add a Twitter or try adapting the code to take Instagram Video posts as well as images. Alternatively, simply use the code to create an infinite feed of your blog posts. The sky is the limit, you can really go to town on this!
As always get in touch with feedback if I have missed a trick somewhere! You can see the full code for this SvelteKit Instagram Infinite Scroll tutorial on the Rodney Lab Git Hub repo .
🙏🏽 SvelteKit Infinite Scroll: Feedback #
Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also, if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.