How to stop SWFs caching in the browser once and for all

As Flash and Flex developers know all too well, browsers have a habit of caching SWFs so that when you put up a new version it doesn’t always show up on client machines.  There are two classic ways to get around this – either by manually clearing your cache (and telling your clients to do the same) or by appending a random number to the end of the filename as a parameter which is then ignored by the application but fools the browser into thinking that the file has changed.  The first method is unreliable and the second method causes the SWF to reload every time you visit the page (even if it hasn’t changed) which munches up your bandwidth and your time.

As it turns out, there is a third and far superior way!  With a tiny bit of PHP in your embed code you can make browsers refresh the SWF only when it has changed.  Note that this uses the SWFObject library, but would work equally well with any embedding method.

   1: swfobject.embedSWF("MySWF.swf?version=<?php echo filemtime('MySWF.swf'); ?>", "myDiv", "100%", "100%", "10.0.0");

It works by using the file modification timestamp of the swf as the version number with the result that browsers will refresh their cached copy if and only if you replace the swf with a new version.  Simple and extremely useful!

5 comments

  1. This is really handy and the best solution I’ve seen – thanks!

    I guess we should note that this only covers the main shell swf… not the swfs loaded within that one at runtime.

  2. With a little fiddling this could be extended to work for shell swfs too – if, for example Shell.swf loads ChildA.swf and ChildB.swf then we could pass in two FlashVars to Shell.swf:

    var flashvars = {
    childAVersion: ,
    childBVersion:
    }

    and then when Shell.swf loads in the swf it just needs to append ?version=whatever to the filename. This should give the same functionality for shell scripts (as long as you know in advance what children you are loading).

    Dave

  3. I prefer to use a md5 hash on the file serverside.
    That technic permits the file to be evaluated on its contents more than its date.
    The better should also to modify the eTag HTTP headers in concordance with this.

  4. You just made my day! been having this problem with flashdevelop debugger not catching on in the right places of the file (seemed to be using old / cached files). This oneliner fixed that! thank you 🙂

  5. Very Very Cool …I have been looking for a good solution. This is the best I have seen so far! Thanks so much for this post!

    Josh

Leave a Reply

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