Zhen
Zhen

Reputation: 12431

How to optimize loading of images on web/mobile web when scrolling

I am now loading all the images via my template when the image loads

 //For example, I will just pass the image url into the tempate when the page renders
  %div{class: "img_container <%= answer.image_scale %> <%=answer.show_image%>"}
    <% if (media_con.standard_resolution) { %>
    %a.fancy{href: "<%= media_con.standard_resolution %>"}
      %img{src: "<%=media_con.standard_resolution%>"}

I realize that by doing this (esp if I am loading many images on the page), it causes inefficieny esp apparent on the mobile web.

How can I load images only when they are in view (scrolling), maybe just load a thumbnail image and load the actual image when the view with the image comes to view.

Any advice here is appreciated

Upvotes: 1

Views: 279

Answers (1)

jevakallio
jevakallio

Reputation: 35960

There are a number of libraries to achieve this. I've personally used the Lazy Load Plugin for jQuery (demo). Instead of setting <img src> property in the template, you should set a property called data-original to the url of the image:

%img{data-original: "<%=media_con.standard_resolution%>", src="placeholder.png"}

And on the client side code (perhaps in Backbone.view.render) you initialize the library:

$("img[data-original]").lazyload();

Upvotes: 1

Related Questions