It is not difficult to find yourself programming a beautiful AJAX web page and realizing you have to reload an image, because it has been changed in the server.
As you use AJAX in your web site, it is not desirable to make the user reload the page for just viewing an update image (not cool at all).
At this point you do some tests, you try to change the “src” attribute of the img tag, you try to remove the previous img and create a new one… but all your effort is useless. The browser has cached the image the first time that was accessed.
Probably the first idea that comes to your mind is, well, if I cannot reload the image, then I’ll make the server generates a new one (with a different name each time), and I’ll load that image with a different name.
You know this is not the best way of doing things, right?
Fortunately there is another easy solution to this: just add a query string at the end of the image src, that changes each time. That would be enough
To make this clear, if your original image has been loaded like this:
<img id="ExampleImage" src="http://server/path/to/image.png" alt="" />Then you should try to reload the image this way:
<img id="ExampleImage" src="http://server/path/to/image.png<strong>?nocache=1</strong>" alt="" />
And then, increment the nocache value on each request.
Using jQuery, the code will look something similar to:
$("ExampleImage").attr ('src', imageSource + "?nocache=" + (g_id++));
I’ve seen forums with this kind of question, so I hope this helps someone
Español
17/12/2008 at 2:45 am Permalink
Hola Pau!
Te leo desde que te “hizo publicidad” Héctor en su twitter… (la de vueltas que dan las recomendaciones!).
Enhorabuena por el blog. Es estupendo. Tiene el nivel de detalle justo que lo hace interesante de leer. !Por fin un blog de programación que no es del estilo super-friki de “mira lo que pasa en el kernel de linux cuando cambio este flag”¡. Y también genial lo de “código manso”. Un nombre con gancho.
Estupendo el post. Muy curioso y muy útil. El “ejemplo ilustrativo” realmente ilustra
Un abrazo y buena suerte en todos tus proyectos!
Domingo.
17/12/2008 at 9:39 am Permalink
Hola Domingo!
La verdad es que intento tocar un poco de todo, aunque como últimamente me estoy orientando a la web, creo que la mayoría de artículos irán por ahí, eso si, siempre desde una perspectiva general. De todos modos, tengo algún que otro artículo en el horno, cuyo “target” es muy muy limitado.
Muchas gracias por el comentario!
Me alegra que te guste el blog
Un saludo!
17/12/2008 at 11:27 pm Permalink
classic trick! Últimamente hay tantas “caches” a tantos niveles en la red que da miedo
29/12/2008 at 3:40 pm Permalink
No es que sea mejor truco pero es frecuentemente usado y te evita tener que manejar contadores: usar el tiempo (fecha y hora).
Por ejemplo:
url = url + ‘?t=’ + (new Date()).getTime();
o incluso:
url = url + ‘?’ + (new Date()).getTime();
En el segundo caso el tiempo, en formato Unix, sería el nombre de la variable con valor null.
02/01/2009 at 12:12 pm Permalink
Ciertamente el truco de usar la fecha es probablemente el más utilizado.
El único inconveniente a nivel teórico, que no práctico, sería si se realizaran dos peticiones en el mismo milisegundo, pero vamos, no es algo que en la práctica vaya a ocurrir.
06/10/2009 at 3:21 pm Permalink
Excelente. Simplemente excelente.