How To Make IE Cache Less

Internet Explorer is known to cache the responses of GET calls. The problem occurs if your javascript functions request the same url over and over again. Internet Explorer will cache the response of the first call, and subsequent calls will automatically return the same response, without actually contacting the server. There are two approaches to solve this problem.

One approach could be to add a random part to the url (i.e.: /poll?random=f2dee87716f). So, the browser will think of it as a different URL everytime. An alternative approach could be to set the response headers correctly. The HTTP headers that need to be set are as follows:


Expires: Sun, 19 Nov 1978 05:00:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

Here’s how I do it in TurboGears. To each method that I don’t want IE to cache, I add the strongly_expire decorator, like this:


    @expose()
    @strongly_expire
    def cant_cache_me(self, position):
        ...

The code of the decorator, which is responsible to set the headers propertly:


def strongly_expire(func):
    """Decorator that sends headers that instruct browsers and proxies not to cache.
    """
    def newfunc(*args, **kwargs):
        cherrypy.response.headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT'
        cherrypy.response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
        cherrypy.response.headers['Pragma'] = 'no-cache'
        return func(*args, **kwargs)
    return newfunc
This entry was posted in howto, turbogears. Bookmark the permalink.

7 Responses to How To Make IE Cache Less

  1. Pingback: From here to eternity » Blog Archive » Serving files with Cherrypy and the browser cache?

  2. Pingback: Making a Flickr Killer With TurboGears - Part 2: A Flickr Clone in 37 Minutes Flat · Nadav Samet's Blog

  3. SeriousUser says:

    Where did you add your decorator definition? The code for
    def strongly_expire(func):

  4. Nadav says:

    Just in the top of the controller module.

  5. SeriousUser says:

    Thanks for your reply. I tried implementing this in my code but it just seems to break it. Without adding the decorator, I am receiving the data fine in JSON format. However, if I include the
    @strongly_expire
    before my function header, it seems to break it and no data comes through. Any thoughts?

  6. SeriousUser says:

    Sorry, I made such a novice error. Please disregard the previous message. Thank you for providing this code snippet.

  7. Admiyn says:

    this post was helpful to me,
    thanks for everybody posting here

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>