AJAX on Mobile
Mobile networks are unreliable. Cache AJAX responses locally and implement retry logic for resilience on poor connections.
Mobile networks are unreliable. Cache AJAX responses locally and implement retry logic for resilience on poor connections.
const cache = {};
function cachedGet(url, ttl = 60000) {
if (cache[url] && Date.now() - cache[url].ts < ttl)
return $.Deferred().resolve(cache[url].data).promise();
return $.getJSON(url).done(data => { cache[url] = { data, ts: Date.now() }; });
}
// Retry on failure
function ajaxWithRetry(opts, retries = 3) {
return $.ajax(opts).catch((_, status) => {
if (retries > 0 && status === "error")
return new Promise(r => setTimeout(r, 1000)).then(() => ajaxWithRetry(opts, retries-1));
return Promise.reject(status);
});
}
On mobile, cache responses aggressively and show stale data rather than a loading spinner — UX is better.