Categories
Article

Lazy Loading Images in Svelte

One easy way to improve the speed of a website is to only download images only when they’re needed, which would be when they enter the viewport. This “lazy loading” technique has been around a while and there are lots of great tutorials on how to implement it. But even with all the resources out there, implementing lazy loading can look different depending on the project you’re working in or the framework you’re using. In this article, I’ll use the Intersection Observer API alongside the onLoad event to lazy load images with the Svelte JavaScript framework. Check out Tristram Tolliday’s introduction to Svelte if you’re new to the framework. Let’s work with a real-life example I put this approach together while testing the speed on a Svelte and Sapper application I work on, Shop Ireland. One of our goals is to make the thing as fast as we possible can. We hit a point where the homepage was taking a performance hit because the browser was downloading a bunch of images that weren’t even on the screen, so naturally, we turned to lazy loading them instead. Svelte is already pretty darn fast because all of the code is compiled in advance. But once we tossed in lazy loading for images, things really started speeding up. This is what we’re going to work on together. Feel free to grab the final code for this demo from GitHub and read along for an explanation of how it works. This is where we’ll end up by the end: CodePen Embed Fallback Let’s quickly start up Svelte You might already have a Svelte app you’d like to use, but if not, let’s start a new Svelte project and work on it locally. From the command line: npx degit sveltejs/template my-svelte-project cd my-svelte-project npm install npm run dev You should now have a beginner app running on http://localhost:5000. Adding the components folder The initial Svelte demo has an App.svelte file but no components just yet. Let’s set up the components we need for this demo. There is no components  folder, so let’s create one in the src folder. Inside that folder, create an Image folder — this will hold our components for this demo. We’re going to have our components do two things. First, they will check when an image enters the viewport. Then, when an image does enter, the components will wait until the…

Read the rest Lazy Loading Images in Svelte

Read at the original Source: css tricks.