Skip to content

Loading on Demand

When working with large family trees, loading everything at once can slow things down and overwhelm users. Fortunately, Family Tree JS 2 supports on-demand loading, letting you load parts of the tree only when needed. In this post, we’ll walk through how to implement this using a simple example.

What We’re Building

We’ll display a family tree that loads new branches only when the user clicks to expand them. This keeps performance smooth and minimizes data usage.

The Key Concepts

  • onDemand(): Triggers when nodes are expanded.
  • fetch(): Retrieves new data from the server.
  • addFamilyMembers(): Adds new nodes to the tree.
  • draw(): Renders the tree.

The Code Explained

javascript
let familyTree = new FamilyTree2(document.getElementById('tree'));
familyTree.readOnly = true;
familyTree.mode = 'dark';
familyTree.templateName = "kitkat";

We initialize the tree in read-only mode with a dark theme.

javascript
familyTree.onNodeClick(function(args){    
    if (this.readOnly){
        this.centerNodes([args.node]);
    }
});

Clicking a node will center it in the view.

javascript
familyTree.onSvgClick(function(args){
    this.fit();
});

Clicking the background zooms out to fit the whole tree.

Loading on Demand

Here is the core part:

javascript
familyTree.onDemand(function (args) {
    for (var id of args.ids) {                    
        this.addFamilyMembers([{ id: id, loading: true }]);
    }
    this.draw(this.focusId, null, function(){
        this.fit();
        fetch(`https://familytree.balkan.app/FetchFamilyMemebers/c8sshc/${args.ids.join(',')}`)
            .then((data) => data.json())
            .then((data) => familyTree.addFamilyMembers(data).draw())
    });
});
  1. Show loading placeholders for the new nodes.
  2. Fetch the real data asynchronously.
  3. Update the tree with the newly fetched members.

Switching Focus

javascript
familyTree.onFocusButtonClick(function (args) {
    fetch('https://familytree.balkan.app/FetchFamily/c8sshc/' + args.newFocusId)
        .then((data) => data.json())
        .then((data) => familyTree.addFamilyMembers(data).draw(args.newFocusId, null, familyTree.fit));
    return false;
});

This lets users navigate to a new person’s family on click.

Initial Load

javascript
fetch('https://familytree.balkan.app/FetchFamily/c8sshc/Q317521')
    .then((data) => data.json())
    .then((data) => familyTree.addFamilyMembers(data).draw('Q317521'));

Finally, we start by loading the root person (Q317521).


Final Thoughts

On-demand loading makes your family tree faster and more scalable. It’s easy to set up and greatly improves the user experience.

Loading on demand doc page