Only load Grid when Details opened

Hi,
I am trying to improve my program’s performance. One of my views displays many Details components which get added to a div container in the afterNavigation method. Every Details component has a complex grid. When I navigate to this view it takes about 4 seconds even if all the Details components are closed (I think every grid gets loaded). Without the grids it only takes half a second. Is there a way to only load a grid when the relevant Details component is/gets opened?

It kind of works if I set the visibility to hidden when the Details component gets closed, but it is a little bit buggy if I open it again (I am using Vaadin 14).

Thanks in advance!

You have different ways of doing this.

You can build the details and add an empty grid. As you don’t fetch the data it should be faster.
When you open the details, you can fetch the data.

You can also build the details and create + add the grid when you open the details:


@Route("details")
public class GridInDetailsView extends VerticalLayout {

    private Grid<String> grid;

    public GridInDetailsView() {
        List<String> items = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            items.add(" item" +i);
        }
        Details details = new Details();
        details.setSummaryText("Grid on open");
        details.addOpenedChangeListener(e -> {
            if (grid == null) {
                grid = new Grid<>();
                grid.setItems(items);
                grid.addColumn(i -> i).setHeader("Column 1");
                details.addContent(grid);
            }
        });
        add(details);
    }

}

Thanks Jean-Christophe! The second option worked. Navigating between views is a lot faster.

Now another thing is bothering me again that I thought I had solved. It is very important that the page scrolls to the details component that was used last. The problem is that the grids in the Details components are not finished with loading (When I enter the view, I open all Details components that were opened last time!) before the scroll method is called in the afterNavigation() method.

Is there a way to call the scroll method after the page finished loading? I already tried onAttach() but that gets called before afterNavigation(). It only works sometimes with a timeout:

UI.getCurrent().getPage().executeJs(
        "setTimeout(function(){ document.getElementById(\"" + id + "\")" +
                ".scrollIntoView(); }, " + milliseconds + ");"
);

Does anybody know a solution to this problem?