; last updated - 2 minutes read

This is a nice little trick a colleague of mine found out. Consider a JSF page that uses a major backing bean. Suppose it takes a long time to initialize this bean (e.g., because a huge amount of data have to be loaded from the database). The JSF page is shown when the backing bean has been initialized completely.

We were looking for a way to decouple the JSF page rending and the initialization. The idea was to show a rudimentary JSF page at once (e.g. the page is shown completely, but some data tables are empty). Once the backing bean has finished it's initialization the missing data is inserted.

To do so you can use Primefaces poll component. Put the long-lasting initialization into a public method that is not called by a constructor, a getter or a @PostConstruct method. Put a poll element behind the data table. The poll component calls your new public method. To make sure the method is called only once, add an onstart="myPoll.stop()". To make sure your method is called early add interval="1".

There is a drawback to this approach: the client initiates the initialization, and it is delayed by at least a second. You can avoid this by starting a new thread doing the initialization in the backing bean's constructor. You save a second, but this approach is far more complex, especially when you try to debug your code. If you can afford to wait an extra second, better keep your code simple.

Update

You can also use Primefaces remoteCommand to implement a better and simpler version to do lazy loading.

Update February 26, 2019

It goes without saying you can do the same trick with BootsFaces, using either <b:poll> or <b:remoteCommand>.


Comments