How to prefetch image in GWT?

时光毁灭记忆、已成空白 提交于 2020-01-01 08:58:08

问题


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?


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/4155364/how-to-prefetch-image-in-gwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!