AJAX is an awesome tool. AJAX requests are usually faster than regular page loads and allow for a wealth of dynamism within a page. Unfortunately many people do not properly cache request information when they can. Let me show you how I cache AJAX requests -- it's super easy!
AJAX是一个了不起的工具。 通常,AJAX请求比常规页面加载要快,并且可以在页面内进行大量动态处理。 不幸的是,许多人在可以的时候没有正确地缓存请求信息。 让我向您展示如何缓存AJAX请求-超级简单!
My example will use my TwitterGitter plugin to grab a user's tweets. Once we have the user's tweet information, we pull it from cache instead of making a duplicate AJAX request.
我的示例将使用我的TwitterGitter插件获取用户的推文。 一旦获得了用户的tweet信息,便将其从缓存中拉出,而不是发出重复的AJAX请求。
Note that before we make the AJAX request, we check the cache object to see if we've saved this key's (the key, in this case, is the username because it is unique) information. If so, avoid the repetitive AJAX request and simply return the cached information. If the key does not exist, make the AJAX request and save the result to the cache.
请注意,在发出AJAX请求之前,我们检查缓存对象以查看是否保存了该密钥的信息(在这种情况下,该密钥是用户名,因为它是唯一的)。 如果是这样,请避免重复的AJAX请求,并仅返回缓存的信息。 如果密钥不存在,请发出AJAX请求并将结果保存到缓存中。
Take a look at this flow:
看一下以下流程:
User requests "davidwalshblog" tweets. @davidwalshblog tweets don't exist in cache, so we go grab them from Twitter and store them in cache.
用户请求“ davidwalshblog”推文。 @davidwalshblog推文在缓存中不存在,因此我们从Twitter抓取它们并将其存储在缓存中 。
User requests "mootools" tweets. @mootools tweets don't exist in cache, so we go grab them from Twitter and store them in cache.
用户请求“ mootools”推文。 @mootools tweets在缓存中不存在,因此我们从Twitter抓取它们并将其存储在cache中 。
User requests "davidwalshblog" tweets again. @davidwalshblog tweets DO exist in cache, so we retrieve them from cache and avoid the ajax request.
用户再次请求“ davidwalshblog”推文。 @davidwalshblog推文确实存在于缓存中,因此我们从缓存中检索它们,并避免了ajax请求。
Clearing the cache periodically is easy too!
定期清除缓存也很容易!
(function() { cache = {}; }).periodical(1000 * 60 * 10); //10 minutesCaching your AJAX results in a JavaScript object is a very simple system to implement and can save you many repetitive requests. Efficiency FTW!
将AJAX缓存在JavaScript对象中是一个非常简单的系统,可以节省很多重复的请求。 效率FTW!
翻译自: https://davidwalsh.name/cache-ajax