Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT code-splitting pattern for ClientBundle image resources

In my GWT large project, I have a ClientBundle for my image resources. I defined about 40 GIF files inside it. (size of each file is about 5KB)

Then I create a class with a static method to set the proper image to the obj that get as parameters:

 public static void setImageFromId (String id,final Image img) {

    //for 1.gif
    if (id.equals("1")) {
        GWT.runAsync(new RunAsyncCallback() {
            @Override
            public void onFailure(Throwable reason) {}
            @Override
            public void onSuccess() {
                img.setResource(MyImages.INSTANCE.img1()); //MyImages is the ClientBundle
            }
        });
    }             

 }

    //for 2.gif
    if (id.equals("2")) {
        GWT.runAsync(new RunAsyncCallback() {
            @Override
            public void onFailure(Throwable reason) {}
            @Override
            public void onSuccess() {
                img.setResource(MyImages.INSTANCE.img2()); //MyImages is the ClientBundle
            }
        });
    }             

   //etc. for other images 3, 4, 5, ...
   //...

 }

I want to know is it good pattern for code-splitting? because if I don't do it all the 40 files will be cached to client browser in first call, but it is not necessary.

RGDS

like image 444
Nav Avatar asked Nov 15 '22 04:11

Nav


1 Answers

So you're trying to avoid downloading each image when your page loads. That's good, if you don't know ahead of time whether every image will be needed.

But, what your code is doing is using code-splitting to only download the code to display your images when the image is needed, which as you can see, is only one line of code per image.

Try this code:

if (id.equals("1")) {
  img.setSrc(MyImages.INSTANCE.img1().getUrl());
} else if (id.equals("2")) {
  //.. and so on.
}

Your images will only be downloaded and displayed when the relevant image is needed. You can use Firebug or Chrome's Developer Tools to see when your images are being downloaded, they should only be requested when needed.

If you have any more questions or find that all your images are being downloaded on page load, let me know and I'll edit my answer again to help you out.

like image 73
Jason Hall Avatar answered Jan 05 '23 01:01

Jason Hall