Anand
Anand

Reputation: 3770

How to make all images on rails view page load asynchronously?

I have a rails 4.2.3 app where I get images from various sources (feedjira, onebox gems) onto the page. Some images may be cached, and can be loaded as usual. But if there are a lot of those on one page, the page load takes a long time. So, from client javascript/jquery, I want images that go out to make a request to the src link to be intercepted, request aborted, src replaced with a transparent gif, and the image downloaded asynchronously. The pseudocode I want is something like follows:

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.requesting) { 
    this.request.abort();
    this.src = "//path/to/actual/image.jpg";
  }
});

Specifically, I am looking for the real world equivalents of the fictitious requesting state and request.abort method in the above code. Am also open to alternate suggestions from rails/jquery libraries/plugins/code.

If at all relevant, I am using turbolinks, but can disable it on these image loads if it poses a problem.

Upvotes: 0

Views: 959

Answers (1)

dennis
dennis

Reputation: 2020

For this I usually build a preloader. By default load a .gif from your asset_pipeline to reduce load time and on DOM ready load the external source:

In your view:

<% @pictures.each do |picture| %>
  <%= image_tag('loader.gif', class: 'preloaded-picture', data: {source: picture.source}) %>
<% end %>

In your javascript/jQuery:

$(document).ready(function(){
  $.each($('.preloaded-picture'), function(index, obj){
    var img = new Image();
    img.src = $(obj).attr('data-source');

    $(img).ready(function(){
      $(obj).attr('src', img.src);
    })
  })
});

Upvotes: 2

Related Questions