feat: add force cache

This commit is contained in:
Enix 2019-11-01 18:40:01 +08:00
parent 479f90aefb
commit 0bc1391148
No known key found for this signature in database
GPG key ID: FE06F5DFC1C9B8E4
3 changed files with 15 additions and 1 deletions

View file

@ -179,6 +179,11 @@ declare namespace Pjax {
requestParams?: IRequestParams[];
formData?: FormData;
}
/**
* Cache accessed pages
*/
forceCache?: boolean
}
export type Switch = (oldEl: Element, newEl: Element, options?: IOptions, switchesOptions?: StringKeyedObject) => void;

View file

@ -23,7 +23,7 @@ var Pjax = function(options) {
this.log("Pjax options", this.options);
if (this.options.scrollRestoration && "scrollRestoration" in history) {
history.scrollRestoration = "manual";
history.scrollRestoration = "auto";
}
this.maxUid = this.lastUid = newUid();

View file

@ -1,8 +1,11 @@
var updateQueryString = require("./util/update-query-string");
const cache = new Map();
module.exports = function(location, options, callback) {
options = options || {};
var queryString;
var forceCache = options.forceCache || false;
var requestOptions = options.requestOptions || {};
var requestMethod = (requestOptions.requestMethod || "GET").toUpperCase();
var requestParams = requestOptions.requestParams || null;
@ -11,9 +14,15 @@ module.exports = function(location, options, callback) {
var request = new XMLHttpRequest();
var timeout = options.timeout || 0;
if (forceCache && cache.has(location)) {
callback(cache.get(location), request, location, options);
return;
}
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (forceCache) cache.set(location, request.responseText);
callback(request.responseText, request, location, options);
} else if (request.status !== 0) {
callback(null, request, location, options);