Reputation: 1771
I have the following working very nicely, loading a partial on click of a link. I'm having trouble however modifying this so that the partial loads on document ready or similar. I basically want to load my slow loading partials asynchronously. Can anyone point me in the right direction please? I feel like it's probably a small modification to make this happen.
#ProductsController
def show_territories
respond_to do | format |
format.js {render :layout => false}
end
end
#products/show.html.erb
<%= link_to 'Show Territories', show_territories_product_path(:id => @product.id), :remote => true %>
<div id="spinner" class="spinner"><%= image_tag("ajax-loader-2.gif") %></div>
<div id="territories" class="tab-contents"></div>
#products/show_territories.js.erb
$( "#territories" ).html( "<%= escape_javascript( render( :partial => "territories") ) %>" );
#products/_territories.html.erb
<!--- partial view code goes here --->
#custom.js
$(function(){
// hide it first
$("#spinner").hide();
// when an ajax request starts, show spinner
$(document).ajaxStart(function(){
$("#spinner").show();
});
// when an ajax request complets, hide spinner
$(document).ajaxStop(function(){
$("#spinner").hide();
});
});
Upvotes: 2
Views: 2153
Reputation: 4216
I've been trying some stuff out based on the code of rails's jquery-ujs (handleRemote method). It seems this works quite nicely and has no need of putting an actual link in the page:
$(function() {
var tmpElement = $(document.createElement('a'))
tmpElement.data('remote',true)
tmpElement.prop('href', '<%= j show_territories_product_path(id: @product.id) -%>')
$.rails.handleRemote(tmpElement)
})
Upvotes: 1
Reputation: 3237
Well you could simply trigger the partials loading manually by calling click() on them.
<%= link_to 'Show Territories', show_territories_product_path(:id => @product.id), :remote => true, :id => 'territories_link' %>
$(function(){
// hide it first
$("#spinner").hide();
$('#territories_link').click();
...
});
Upvotes: 3