To improve performance of a web application we need to reduce server & client communication as much as we can. This technique helps to improve performance of a web application. Always it’s wise for a programmer to store static data in client browser. Except for the first time but every time while user will request the same page from the serve we need to check whether the similar data exists in the client memory or not. If the similar data exist in the client memory we need to load this data to reduce server & client communication. In this way to achieve this we need to store our static data in the client browser memory. To make this process easier HTML5 introduced Local Storage. Which stores data in client browser for the unlimited time we want. Compare to session storage html5 local storage stored data after user interaction. I can say html5 local storage is like a offline data store.
During web application development we do integrate many images to our application to make our application more user attractive. Here images are static data. If the user is requesting the similar page 10 times from his/her browser we need to avoid server interaction for nine times rather then for the first one. So in this session let us know how to save image in html5 local storage.
In the below example I am storing an image to HTML5 local storage. In HTML body here I have 2 images imageToLoadInLocalStorage & imageToShowFromLocalStorage. The first image has a src attribute which loads a png image (global-img.png) from server. Second image is having blank src attribute. Using client script here I am storing the first image to local storage & fetching the similar image from local storage to my second image. The mechanism I used here is I am fetching the first image using DOM object method getElementById. Converting the image to Base 64 data url format & storing it to local storage using localStorage.setItem() method. Then fetching the image from local storage using localStorage.getItem() method & assign the image to my second image control.
To run the below example copy the codes into a notepad file. Save it as HTML. Then open the file using any browser which supports HTML5 storage. Before run the below app make sure you are with internet connectivity.
Example to save image using HTML5 Local Storage