问题
When a user clicks a button on my site, a particular part of a page will be refreshed, but it takes a while to render the entire section. Is it possible to display/output parts of the section in real time rather than wait for the entire section to finish? How would i do this if im sending it as an ajax request for html content? Thanks
回答1:
I would recommend setting cache: true
in your AJAX call (if using jQuery) and either way, you're going to want to set the HTTP response headers. Here are some examples. By setting the cache-control
headers and expires
etc, your AJAX requests - if unchanged - will be loaded from cache instead. This will drastically speed things up.
A quick example:
if (!headers_sent()) {
// seconds, minutes, hours, days
$expires = 60*60*24*14;
header('Pragma: public');
header('Cache-Control: maxage=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
}
Note: this will not work with POST requests, just GET.
回答2:
As said, caching your AJAX requests is a good option. Besides that, all I think you can to do make your application seem faster is to show users a progressbar while (re)loading content with AJAX.
回答3:
You could implement a Pagelets technique. Essentially you could work this in a way, like below:
index.html
Ajax -> load content from PHP script which outputs the navigation bar
Ajax -> load content from PHP script which outputs the body
And have several different Ajax calls loading each different part of your site. This does have a disadvantage of increasing the amount of HTTP requests the user's browser has to make, however.
This is presuming though that different parts can be generated separately from the rest of the page. If all your content needs to be generated at the same time then this technique will be of no use to use.
This is of a good read (Facebook project named "BigPipe"): http://www.facebook.com/note.php?note_id=389414033919
来源:https://stackoverflow.com/questions/8107883/output-buffering-and-ajax