Simple way to avoid caching in Javascript
Thursday, December 5, 2013 at 03:35AM
Carl Franklin

This is a tried and true method to avoid a situation in which you want to make a call to a static url which may return a different result each time. Simply append an argument to the url with a random or otherwise unique string as the value.

Consider this javascript function:

        function getUniqueString()
        {
            var d = new Date();
            return d.getTime().toString();
        }

This will return a unique string every time that you call it.

Now, suppose you are calling a url that looks like this:

        var url = "http://myserver.com/getSomeImage";

It may work the way you expect in one browser but not in another.  Just append an argument to it like so:

       var url = "http://myserver.com/getSomeImage?cacheKiller=" + getUniqueString();

The url might look like this:

       http://myserver.com/getSomeImage?cacheKiller=1386232969279

Well done!

 

 

Article originally appeared on Carl Franklin (http://carlfranklin.net/).
See website for complete article licensing information.