Loading on Demand with animation in Family Tree JS 2
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.
Code Example
🔧 What We’re Building
We’ll display a family tree that loads new branches only when the user clicks to expand them. This way, performance stays smooth, and data usage is minimized.
🧩 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
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.
familyTree.onNodeClick(function(args){
if (this.readOnly){
this.centerNodes([args.node]);
}
});
Clicking a node will center it in the view.
familyTree.onSvgClick(function(args){
this.fit();
});
Clicking the background zooms out to fit the whole tree.
🌱 Loading on Demand
Here's the magic:
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())
});
});
Show loading placeholders for the new nodes.
Fetch the real data asynchronously.
Update the tree with the newly fetched members.
🔄 Switching Focus
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
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