HTML5 code example: Intelligently store Images in localStorage for faster page loads!
bobleah 270000CN12 Comments (22) Visits (117635)
Recently I was exploring lazy load techniques as a method to improve perceived page load times. There are a number of methods to lazy load web artifacts, which enable a web developer to delay or load page elements on demand. Typically these methods are used to control and prioritize the rendering of primary web page elements to the benefit of the overall user experience. My interest was focused on loading page artifacts, including intelligently and selectively storing web page Images. As part of my research, I thought it might be interesting to explore the use of the HTML5 localStorage API.
The corresponding HTML Image element:
You can download the complete HTML of this example by clicking here.
In order to demonstrate the significant improvement in page render time of locally stored artifacts, I have uploaded an online working example. In this example, I render the first image from your browsers local storage, while the second identical image is retrieved from a web server. After you load the example page, perform a few (F5) page refreshes and observe the difference in Image load time. Please note: For demonstration purposes, I have kept this illustration scoped to storing an Image. The realization of page performance is derived by the number, size, and complexity of the stored elements, and in the exercise of intelligent control the server application has on these elements.
This brings us to one of the the key differences between between localStorage cached artifacts vs. browser cached artifacts, which is in the level of fidelity and point of control of the cache itself, I.E. application vs. client. Setting HTTP server-side headers which instruct browsers to keep the content in its local cache is standard fare. But the caching policy remains with the browser. Setting HTTP headers doesn't give applications the fidelity of control or insight to what is truly happening on the client.
Some of the challenges with standard browser caching are:
In addition to intelligent caching where the application can tune and control the client cache for quicker page load times, I can think of a number of examples where this technique can be very useful. For example, if you are developing offline applications, or applications for smart devices where there may not be a persistent connection to your application server. For the complete specification of the HTML5 localStorage API, visit the W3C specification page for Web Storage. Enjoy!