Skip to content

Instantly share code, notes, and snippets.

@AlexandrBasan
Forked from joakimk/controller.rb
Last active June 26, 2022 08:05
Show Gist options
  • Save AlexandrBasan/1c7569ef6f37db4819c2cbe9a2fcc378 to your computer and use it in GitHub Desktop.
Save AlexandrBasan/1c7569ef6f37db4819c2cbe9a2fcc378 to your computer and use it in GitHub Desktop.
A way to lazy load partials in Rails 4
class Controller
include LazyLoad
def show
@model = Model.find(...)
respond_to do |format|
format.html do
@html_specific_data = Model.find(...)
end
render_lazy_load(format) do
@lazy_specific_data = Model.find(...)
end
end
end
end
module Helper
def lazy_render(name)
content_tag :div, :id => "lazy-loaded-#{name.gsub('/', '-')}" do
content_tag :div, :class => "spinner" do
content_tag(:script) do
"if(!window.lazyLoads) { window.lazyLoads = []; }; window.lazyLoads.push('#{name}');".html_safe
end
end
end
end
end
module PartialLazyLoad
def render_lazy_load(format, &block)
format.js do
block.call if block
if !params[:search]
render json: { lazy_load_partial: params[:lazy_load_partial], body: render_to_string(:partial => params[:lazy_load_partial]) } if params[:lazy_load_partial]
end
end
end
end
<!-- LazyLoad for partials -->
<!-- https://gist.github.com/AlexandrBasan/1c7569ef6f37db4819c2cbe9a2fcc378 -->
<script>
var i, lazyLoad, len, ref, url, host;
if (window.lazyLoads) {
ref = window.lazyLoads;
for (i = 0, len = ref.length; i < len; i++) {
lazyLoad = ref[i];
host = location.protocol + '//' + location.host + location.pathname; // window.location.href.split('#')[0]
url = host + ("?format=js&lazy_load_partial=" + lazyLoad);
$.ajax({
url: url,
dataType: "json",
success: function(data) {
var element = $("#lazy-loaded-" + data.lazy_load_partial.replace(/\//g, '-'));
element.removeAttr('align');
return element.html(data.body);
},
error: function(JSONHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus + ". Error: " + errorThrown);
return $("#lazy-loaded-" + lazyLoad.replace(/\//g, '-')).html('<i class="fa fa-ban fa-2x"></i>');
}
});
}
window.lazyLoads = [];
}
</script>
<!-- LazyLoad for partials -->
= render 'foobar'
becomes
= lazy_render 'foobar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment