Wordpress Snippets

Prevent Browser Caching Image Files

When you are developing a site, you have to refresh page lot of times and you start to get a pretty good feel for what your browser is going to pick up on a single refresh, and what it won’t. For example, I find that if I overwrite an image file on the server, it will take me two refreshes for that image to update on the live site. And if it’s still showing a really old version, Refresh. Refresh. Refresh.

That’s fine for you, but if you are showing website to a client and he keeps getting back at you that changes are not visible. Then every time you will ask you client to clear the cache by ctrl + F5 or any other means. I know it’s frustrating but can we do something to prevent browser caching images temporarily.

Well, we can. A common and simple solution to this problem is to append image URLs with a dynamic query string. So from the point of view of the server the same file is accessed, but from the point of view of the browser no caching will be performed and browser will download image again.

Now in this below example we are appending image URL with query string “?v=” and current time stamp. It will make sure that browser will always download image.png on each refresh and not pull it from cache. It will prevent browser caching for targeted images.

<img src="http://wpcodesnippet.com/path/of/the/image/folder/image.png?v=<?php time(); ?>" alt="Image Title" />

Same techinique can be applied to CSS and JavaScript files too.

<link rel="stylesheet" href="http://wpcodesnippet.com/path/of/the/css/folder/style.css?v=<?php time(); ?>" type="text/css" media="all" />

<script type="text/javascript" src="/path/of/the/scripts/folder/scripts.js?v=<?php time(); ?>"></script>

Hire Us. Or just say Hi!
Need a job? Apply to get one.