JP Silvashy
JP Silvashy

Reputation: 48495

Rails, rendering partial via JS on page load?

So I understand how to get partials to render when say a link is clicked, but say I want to start loading the partial after the page renders?

show.html.erb

<div id="weather"></div>

weather.js.erb

$( "#weather" ).html( "<%= escape_javascript(render( :partial => 'weather' )) %>");

weather.html.erb

<%= Time.now %> # For brevity. This actually does more.

Controller

def weather

  slow_api_request

  respond_to do |format|
    format.js {render :layout => false}
  end
end

But so then how can I start the request for the partial after the page loads (because the action is pretty slow to retrieve the data from the API), I'm using rails UJS, I just a bit confused.

Upvotes: 2

Views: 2461

Answers (1)

apneadiving
apneadiving

Reputation: 115511

You should simply add an ajax call. Assuming you're using jQuery, just add this kind of scripts in your view:

$.ajax({
  type: "GET",
  url: "<%= url_for your_path %>" ,
  success: function(data){
    //if ever there is something more to do (there is also an error handler)
  }
});

Upvotes: 3

Related Questions