收录日期:2021/02/27 19:45:50 时间:2009-03-14 02:20:57 标签:javascript,ajax,caching,performance

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?

How much information (old entries which the user may return to) dare I save client side using JavaScript considering that they contain HTML for an entire article? Maybe I do not have to save them with JavaScript if I somehow make sure the clients browser cache the AJAX application's state (e.g. getHTML.php?article=4) so that it returns the HTML without really sending an AJAX request (after it has already been requested once)?

Thanks in advance,

Willem

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?

 getHTML.php?article=4

It is silly to reinvent the wheel for such requests.

I think the only things you should cache is data that you know the user will toggle to view. Take for example Digg -- they cache the comments on each submission in the format of an object in Javascript. When the user wants to view this comment, a function simply inserts it into the document in the correct format. However, not all comments are cached. Only the top ones, which are ones most likely to be viewed.

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.

If you really want to you probably can cache each article/page/whatever as a separate JavaScript file containing really lightweight JSON with the HTML contents.