سؤال

Can someone point me to some example code on how best to do caching while loading up the dynamic parts of a page using javascript?

My canonical example involves a page where nothing ever changes other than the user's logged in status and username at the top of the page. Changing this text through jQuery and an ajax request is easy enough, but since I'm doing it on $(document).ready(), if you look quickly, you can see the page load with something like "Click Here to Login" before the ajax request fires and updates that section of the page.

Edit for clarification:

If I cache the entire page, the following happens.

  1. User A requests the page
  2. Page is not cached, so application generates html with "Hi User A" in the upper right corner
  3. User B requests the page
  4. Page is cached, so application serves it us as-is -- including the "Hi User A" bit <- This is the part that I want to dynamically update.

Ideally, at step 2, the page would get cached without the "Hi User A" bit, so that when someone requests the page, I make a simple ajax request to get the greeting and then shove it into the dom.

I'm assuming javascript is the way to go, but I'm thinking there has to be a better way than to wait for $(document).ready() such that the page renders more naturally.

If it matters (though I don't think it should, as a solution that applies to static html would also work for what I'm doing), I'm using rails 2.3.x and jQuery.

هل كانت مفيدة؟

المحلول 2

Aha! There's a railscast that does exactly what I want!

Rails-y goodness can be found here: http://railscasts.com/episodes/169-dynamic-page-caching

نصائح أخرى

I would load the user status initially in the main page on the server, using the same thing that generates the AJAX response. Then when the user changes the status, update it using AJAX client-side.

This way, the initial page has the correct status but can still change when the user performs an action.

Pretend the method getStatus() generates the correct HTML for whatever state the user is in. On the page, I would have a <div> that contains this information. Server-side, call getStatus() (using PHP for example purposes):

<div id="status"><?php =getStatus() ?></div>

Then have your AJAX request return getStatus() and update the <div id="status"> contents.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top