Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prefetch image in GWT?

I tried the following code:

RootPanel root = RootPanel.get("root");
root.clear();
final FlowPanel p = new FlowPanel();
root.add(p);
for (int i=0; i<20; ++i) {
    String url = "/thumb/"+i;
    final Image img = new Image(url);
    img.addLoadHandler(new LoadHandler() {
        @Override
        public void onLoad(LoadEvent event) {
        p.add(img);
    }
});
Image.prefetch(url);

But it does not work for me. Did I missed something?

like image 931
Antonio Avatar asked Nov 11 '10 14:11

Antonio


3 Answers

Image load handler is called only in the case, when image is attached to the DOM. So you have to add image to the DOM outside the loadHandler:

p.add(img);
img.addLoadHandler(new LoadHandler() {
    @Override
    public void onLoad(LoadEvent event) {
        //do some stuff, image is loaded
    }
}
like image 108
dreak Avatar answered Oct 15 '22 04:10

dreak


What Stan said makes sense.

I think the problem is that the LoadHandler isn't being called for some reason. I've always managed without a LoadHandler, but I usually add an errorHandler as per the JavaDoc demo which is triggered if loading fails. This should work:

final Image img = new Image();

img.addErrorHandler(new ErrorHandler() {
      public void onError(ErrorEvent event) {
        // Handle the error
      }
    });

img.setUrl(url);
p.add(img);

See the example in the GWT Javadoc: http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/gwt/user/client/ui/Image.html

like image 45
Joel Avatar answered Oct 15 '22 03:10

Joel


ImageElement img = DOM.createImg().cast();
img.setSrc("images/myImage.png");
like image 1
vinnyjames Avatar answered Oct 15 '22 02:10

vinnyjames