Uploading a lazy image using GWT

JQuery and other JS frameworks got a lot of plugins for loading graphic images, code blocks. Which basically loads the image when it is visible in the visible area of ​​the browser.

How to do it in GWT? I know that I can use the jQuery plugin in GWT, but in search of my own GWT solution.

So, I would like to do something like this.

LazyImage img = new LazyImage("load.gif","original_thumb.png") scrollContainer.add(img); //scrollContainer is added to ScrollPanel 
+6
javascript image gwt lazy-loading
source share
2 answers

Basically a solution from Jason. Except that the image itself decides when it needs to load.

 class LazyImage extends Image { private String fUrl; private ScrollPanel fParent; private boolean fLoaded; public LazyImage(String url, ScrollPanel parent) { fUrl = url; fParent = parent; attachHandlers(); } private void attachHandlers() { fParent.addScrollHandler(new ScrollHandler() { @Override public void onScroll(ScrollEvent event) { int imageTop = getAbsoluteTop(); int viewport = fParent.getAbsoluteTop() + fParent.getOffsetHeight(); if (imageTop < viewport) { lazyLoad(); } } }); } @Override public void setUrl(String url) { fLoaded = false; fUrl = url; } public void lazyLoad() { if (!fLoaded) { super.setUrl(fUrl); fLoaded = true; } } } 
+3
source share

It should be somewhat simple. There are two main steps.

1.) Create a widget that you can scan to download the image programmatically, rather than automatically displaying it. Save the URL of the image you are uploading and enter a method for downloading it.

 public class LazyImage extends Image { private String url; // Override behavior of base Image constructor to just store the URL. public LazyImage(String url) { this.url = url; } public void lazyLoad() { super.setUrl(url); } } 

This can be used just like a regular Image class, except that you will need to call lazyLoad() to get the image.

2.) Detect when an image is needed using the ScrollPanel .

I'm not entirely sure that the code for this does not work, but it basically comes down to comparing the location of the image and the scroll position of the scroll bar. If the scroll position> = the distance to the image from the top of the scroll bar, call lazyLoad() and the image will appear.

I have not tried any of this code, this is just a sketch of what should work. Feel free to ask questions or give feedback if they work / do not work for you.

+1
source share

All Articles