开发者

How to prefetch image in GWT?

开发者 https://www.devze.com 2023-01-24 19:40 出处:网络
I tried the following code: RootPanel root = RootPanel.get(\"root\"); root.clear(); final FlowPanel p = new FlowPanel();

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() {
        @O开发者_C百科verride
        public void onLoad(LoadEvent event) {
        p.add(img);
    }
});
Image.prefetch(url);

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


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
    }
}


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


ImageElement img = DOM.createImg().cast();
img.setSrc("images/myImage.png");
0

精彩评论

暂无评论...
验证码 换一张
取 消