I’ve been putting to gether a little web app recently and wanted to create a jsTree to display data held on the server. Since it’s potentially a lot of data I wanted each level of the tree to load just-in-time, i.e. do what’s called “lazy-loading”. First I coded a version that did this manually, i.e. I added a hook for when each node was openend and then use jQuery to issue an AJAX call to the server to request all the children of that node ID. That worked but felt awkward and, most importantly, because jsTree only lets you add one new child at a time, was slow.
A little looking around on the web revealed that infact jsTree has a built-in way to do ajax loading. This worked well but the problem was that, because the first load would only load the top most level of the tree, jstree had no notion that each node potentially had children and thus failed to put the little “+” sign at each node junction. Thus no click events would be captured and jstree would never attempt to open a node and load more children. It took a whiel tow ork out what’s going on and none of the examples on the web had what I needed. So here’s the solution: