Move, Copy or swap DOM elements?

If you have been reading my posts, you probably already know that I worked on jMatrixBrowse this summer. For those who don't know, it is a jQuery plugin that allows creating browsable matrices (just like Google maps) on the web. See a quick demo here.

An important objective for the plugin was not to make a lot of requests to the backend to obtain the data in the matrix. However, we still wanted to have the data available for the user as soon as he reaches a particular cell. We implemented a background caching module for this that loaded all the cells in the matrix in a separate background container so that all the data is available in the DOM when it is required. This was implemented as a completely separate module which handled all calls to the backend. So the main plugin only made requests to the background loading module and it decided which cells it already had and which it needed to retrieve from the API on the go and sent the results to the renderer.

This was working great. The only thing that we needed to take care of was how to swap in the content from the background to the matrix content. Here are some experimental results from three strategies that we tested.

  • Strategy 1: Load the background data in a separate container and when more cells are required in the matrix, we clone and move the cells from the background container to the main matrix container at the corresponding position.
  • Strategy 2: Load the background data in the same container as the matrix content but make it initially hidden. Change the top/left of the background cells and show them when new data is required in the matrix.
  • Strategy 3: Load the background data in a separate container and when new data is required in the matrix, swap the html of the new data in place of the already existing cells.
|  Reload window   | Strategy  | Average Time (in msec)|
| One Page (5x10)  |     1     |            17         |
| One Page (5x10)  |     2     |             8         |
| One Page (5x10)  |     3     |             4         |
| One Row  (1x10)  |     1     |             4         |
| One Row  (1x10)  |     2     |             1.5       |
| One Row  (1x10)  |     3     |             1         |

As expected the first strategy is the slowest because cloning DOM elements is slow. Strategy 2 was the next slowest because moving content in the DOM is slow as well. The fastest was swapping the HTML content which required just about 1ms for loading one row of cells which is a good response time.

If you want to have a detailed look at how these strategies were implemented, have a look at the jMatrixBrowse code on github.

Published 3 Sep 2012

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter