Lazy Loading Images in Ember

Alex Navasardyan
The Ember Way
2 min readFeb 9, 2015

--

Everyone likes beautifully crafted web sites with high resolution images. 500px, AirBnb, you name it. Having great pictures on your website comes with a cost though. It will slow down the initial loading of your page. You might not notice the performance hit if you have a speedy WiFi connection. But what if you’re on mobile (3G, 4G)? Probably, you’re going to observe an empty page for some time while waiting for the images to load. Not the best UX, eh?

How can we improve our UX and page loading time? We can put all our assets on CDN, suffer the first page load and let browser cache all the assets. Putting the assets on CDN is good idea but we can do better. What if we could load images on demand? In another words, can we postpone loading all the image and load only the ones that we need to show to the user?

Well, it turns out we absolutely can. We can implement something called lazy loading — don’t load the image unless it’s in the view port. In other words, if it’s in the visible area.

I’m not going to go into a great detail of how to detect if the DOM element is in the view port or not. Lauren Tan has a great article about it. I tweaked her original code a bit. Thanks, Lauren!

Sweeeet. Now we have a way to detect if an image is inside the view port. How do we “load” it? Turns out, it’s as easy as setting “src” attribute on an “image” element.

Awesome. We’re almost done. There’s one tiny question left. How can we let user know that image is loading? Let’s say, show the spinner or “loading” message. Luckily, there’s an onload event that we can take advantage of.

Bam! Now we have a way to tell if image is loaded or not. There’s also an onerror event that we can use.

Lazy Image Component

I glued all the pieces together and created Lazy Image Component.

I also wrote an Ember CLI addon to easily share the code with other Ember CLI users.

JSBin Demo

If you find any issues with the code/css (anything really), I would appreciate if you could create a github issue.

--

--