I am building a simple blog which is viewed single-page (do not worry, it is progressively built) and thus I am sending AJAX requests which return HTML to be inserted into the page.
What is the most efficient way to store/cache information (HTML) to be added at a later time into the DOM?
Thanks in advance,
I would recommend that you cache them somewhere inside the DOM itself, either at their natural place or in a "cache"
div, just hide them or their container (
visibility: hidden). Move them around the DOM (e.g.
final_container.appendChild(cache.removeChild(cached_item))) and show them as required. This should give you the best bang for the buck in terms of memory efficiency, speed and simplicity when dealing with moderate amounts of cached information.
With the proper cache directives inside your AJAX replies' headers, the browser might also perform caching for your AJAX replies just like for regular pages.
Check out this Browser-Side Cache article for ideas, too.
Wouldn't it be better to let the browser cache these sort of requests?
It is silly to reinvent the wheel for such requests.
Any information that you can "toggle" to show/hide, these can be cached, and even preloaded. You can also use the
visibility: hidden and
display:none technique as pointed out above. That way, you just transpose them to the DOM and simply show and hide that element when needed.
I agree with Gary that you might question if you really want to go through the effort for this. I'm sure you have a good reason if you really go through with it.