Skip to content

Instantly share code, notes, and snippets.

@dt1973
Last active August 29, 2015 14:17
Show Gist options
  • Save dt1973/50f826681b92c6e60299 to your computer and use it in GitHub Desktop.
Save dt1973/50f826681b92c6e60299 to your computer and use it in GitHub Desktop.

Load media via jQuery instead of on page load

Live app: http://runnable.com/VEEnRTEK-igg4XGD/forem-with-paperclip-for-ruby-on-rails

app/views/forem/posts/_post.html.erb

<% for photo in post.photos %>
  <%#= image_tag photo.attachment.url(:medium) %>
  
  <!-- Speed optimization: Load into `img` tag on client-side later on -->
  
  <div class="load_later" data-url="<%= photo.attachment.url(:medium) %>" style="display: none;"></div>
<% end %>

app/assets/javascripts/application.js

$('.load_later').each(function() {
  var placeholder = $(this),
    url = placeholder.attr('data-url');
  
  // http://stackoverflow.com/questions/4285042/can-jquery-ajax-load-image
  
  var media = $('<img />').attr('src', url).load(function() {
    if(!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
      console.log('Broken media');
    } else {
      media.insertAfter(placeholder);
    }
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment