How to cache Html element with Html5 Canvas and LocalStorage<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to cache Html element with Html5 Canvas and LocalStorage

Posted on: December 7, 2015

This caching idea is limited to some scenarios where you have defined html zones. For example, if you are working with dynamic charts or having a complex logic to render Html controls or even complex canvas. In all cases, the goal is to show to the user something relevant instead of just a loading spinner for the subsequent calls.

The concept is that once you have loaded the zone the first time, you take a snapshot and store it into the local storage as a visual copy -- an image. The idea behind using an image is that you do not have to wait for extra dependencies like JavaScript files, CSS stylesheets or Ajax calls to have something displayed to the user. Meanwhile, the normal flow of your application must continue to have the real html loading with fresh values from the backend. The major advantage of that solution is that you have no slowness because of the network, neither of the server or from complex rendering client side code -- you get it directly pre-rendered from the client side cache.

This article will show you how to take a screenshot,in JavaScript, with the library called Html2Canvas, stores it into the local storage and how to do the swap between this fake cached view with the real Html one. First, let's create an example scenario with two zones. One zone, called box1 will take 3 seconds to load and the box2 will take 5 seconds. The goal is to display the fake cached view when loading the real data, and thus make it appearing to the user as it was already loaded.

This solution is having some caveats. First, if the time between the image and the real html takes too much time, than the user may be confused. Thus, this is a good solution for improving a solution that has good performance on the start. I would say that you can easily use that solution for zones that load without this trick under 3-5 seconds. You can always have a subtle loading visual hint somewhere if it's longer. Second, if the cached image is very different from the new visual, than it will flicker during the swap of the image to the real html. Third, the local storage is limited in size, between 5 to 10 megs. That mean that you are limited to what you can cache with that solution. Overall, this solution is not a silver bullet and should be used as a blazing fast boost experience to an experience that is reasonable to load. It's not a solution to apply to a menu for example, because user may interact very fast with it and would hit a wall or should I say an image. It's good for element in a page that has a high visual interest or with element that has basic interaction like linking to somewhere else because the image can fulfill that contract.

Let's dive in the code.

1<div id="box1" class="box">
2 <i class="fa fa-spinner fa-spin"></i>
4<div id="box2" class="box">
5 <i class="fa fa-spinner fa-spin"></i>
2 width:150px;
3 height:150px;
4 background-color:lightblue;
5 margin:10px;
7 i{
9 font-size: 3em;

This will produce the following html : 2LoadingZonesBoxes

The normal loading experience is done by using JavaScript's timeout. Both box display a different text, one display also an image.

1setTimeout(renderBox1, 3000);
2setTimeout(renderBox2, 5000);
3function renderBox1() {
4 var $box = $('#box1');
5 $box.text('Loaded 1');
6 var $icon = $('<i>').addClass('fa fa-hand-peace-o');
7 $box.append($icon);
10function renderBox2() {
11 var $box = $('#box2');
12 $box.text('Loaded 2');

So far, it takes the amount of time defined to see the spinner being removed and replaced by the real content.

The next step is to have in those render box the code to set the cache with the image of the rendered result. Box 1 will have the text and the image, box 2 just the text. This require to change both render method to call a cache method. Since the experience is so seamless that we will also, for the purpose of this demo, add some text under the boxes once refreshed with real value. So, the visual will be on the first call that we display the spinner, we cache, we display the text under the box. On the second load, we do not display the spinner since this one is replaced by the cached version right away. The texts under the boxes are shown only after the delay with the real value.

1function renderBox1() {
2 var $box = $('#box1');
3 $box.text('Loaded 1');
4 var $icon = $('<i>').addClass('fa fa-hand-peace-o');
5 $box.append($icon); cache($box);
6 $box.after('<p>Not cached data box 1 in place</p>');
9function renderBox2() {
10 var $box = $('#box2');
11 $box.text('Loaded 2');
12 cache($box);
13 $box.after('<p>Not cached data box 2 in place</p>');

We also need to change the loading code to go check in the cache. We try to read the cache, the local storage, and if nothing

1var box1Cached = unDataToCanvas(localStorage.getItem('box1'));
2var box2Cached = unDataToCanvas(localStorage.getItem('box2'));
5 $('#box1').html(box1Cached);
7setTimeout(renderBox1, 3000);
10 $('#box2').html(box2Cached);
12setTimeout(renderBox2, 5000);

Finally, the load and save in the cache need to be coded. The save will create a canvas and we will store the data into a base64 representation. This is done by calling the method toDataUrl() method.

1function cache($elementToCache) {
2 var id = $elementToCache.attr('id');
3 html2canvas($elementToCache, { onrendered: function(canvas) {
4 window.localStorage.setItem(id, canvas.toDataURL());
5 }
6 });

The loading is more tricky. We need to load from the local storage the base64 image, create an image with the source to this base64 and return it.

1function unDataToCanvas(data) {
2 var img = new Image();
3 var canvas = document.createElement('canvas');
4 img.onload = function() {
5 canvas.width = 150;
6 canvas.height = 150;
7 canvas.getContext("2d").drawImage(img, 0, 0);
8 };
9 img.src = data;
10 if(data){
11 return img;
12 } else{
13 return null;
14 }

The whole code with a working demo is on :