Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Last active October 31, 2016 04:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbloom7/a879915f7921a3ca11c3 to your computer and use it in GitHub Desktop.
Save chrisbloom7/a879915f7921a3ca11c3 to your computer and use it in GitHub Desktop.
Bust AJAX request caching

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });

Source: http://stackoverflow.com/a/735101/83743

However, jQuery's AJAX object will follow redirects, so even if you disable caching globally the "_={timestamp}" parameter that jQuery adds to bust the browser's cache may not be forwarded with the redirect. In that case, your request can still be cached by the browser. The solution is to either make sure that special param is passed along with redirects, or to send the appropriate cache-busting response headers from the server-side code for those requests.

Reference: http://api.jquery.com/jQuery.ajax/

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_filter :set_cache_buster_for_xhr
private
# Prevent AJAX requests/redirects from being cached
def set_cache_buster_for_xhr
if request.xhr?
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end
end
end
// public/javascripts/scripts.js
// A javascript file that is included in all requests
jQuery(document).ready(function($){
// Disable caching of *all* AJAX requests
$.ajaxSetup({ cache: false });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment