caching background image

Skip to first unread message


Oct 29, 2012, 2:15:21 PM10/29/12

my app has a background image which is attached to the main panel with the CSS attribute "background-image". I would like to avoid unecessary loading of this image by having it cached in the browsers for a long time.

I know methods for the apache web server, e. g. mod_expires. But my app runs on tomcat and the image resides under the war directory.
What would be a good method to control the caching of this image?


Benjamin Possolo

Oct 29, 2012, 4:35:05 PM10/29/12
If you can, use a ClientBundle. That will ensure the background image only gets downloaded once with the rest of your image resources and the spritemap produced by the client bundle should be cached by the browsers.

create an interface called AppImages that extends ClientBundle (class must be in part of your apps 'client' and visible to the gwt compiler).

public interface AppImages extends ClientBundle {
ImageResource background();

put the PNG in your source folder alongside the AppImages interface.
ideally you would do this for all small-to-moderate sized image resources that your app uses.

When you want to set the background image of an element, you have several ways of doing it (note: i'm writing this without actually testing so it may not be perfect).

1) Use an HTML template to create the element with the background image

public interface HtmlTemplates extends SafeHtmlTemplates {
@Template("<div style=\"background-image: {0};\"/>")
SafeHtml backgroundDiv(SafeUri imageUrl);

HtmlTemplates templates = GWT.create(HtmlTemplates.class);
AppImages images = GWT.create(AppImages.class);

SafeUri backgroundImage = images.background().getSafeUri();
SafeHtml backgroundDiv = templates.backgroundDiv(backgroundImage);

2) Set the background-image css property on the element that underlies the GWT widget.

AppImages images = GWT.create(AppImages.class);
SafeUri backgroundImage = images.background().getSafeUri();

FlowPanel panel = new FlowPanel(); //this creates a div

Remember, you'll probably also want to set the other important css properties like background-repeat, background-position, etc.
Finally, if you want the image to be available publicly on the web, use the <public> declaration in your GWT module descriptor. This will tell the compiler to dump the background PNG into your war/<MODULE_NAME>/background.png folder so you can access it out on the web like

Joseph Lust

Oct 29, 2012, 8:18:53 PM10/29/12
You can set the cache headers from Tomcat using a filter like this example.

Or, you can also set it up in Tomcat7 with the Expiration Headers filter configuration.

Either way, using a Bundle or not, you'll need to follow the best practices for GWT and ensure that only the *.cache files are indeed cached by applying these headers somehow.

Reply all
Reply to author
0 new messages