From 6491e3243787556664dc254dcc55b6af226b6786 Mon Sep 17 00:00:00 2001 From: BehindTheMath Date: Sun, 7 Jan 2018 23:56:11 -0500 Subject: [PATCH] Add an option to set a timeout for XHR requests (#95) Closes #24. --- README.md | 4 ++++ index.js | 1 + lib/proto/parse-options.js | 3 ++- lib/request.js | 5 +++++ 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 34f1659..7e6a1ce 100644 --- a/README.md +++ b/README.md @@ -392,6 +392,10 @@ Useful to debug page layout differences. When set to true, clicking on a link that point the current url trigger a full page reload. +##### `timeout` (Integer, default to 0) + +The timeout in milliseconds for the XHR requests. Set to 0 to disable the timeout. + ### Events Pjax fires a number of events regardless of how its invoked. diff --git a/index.js b/index.js index bd7bc56..24e3df5 100644 --- a/index.js +++ b/index.js @@ -158,6 +158,7 @@ Pjax.prototype = { trigger(document, "pjax:send", options); // Do the request + options.requestOptions.timeout = this.options.timeout this.doRequest(href, options.requestOptions, function(html) { // Fail if unable to load HTML via AJAX if (html === false) { diff --git a/lib/proto/parse-options.js b/lib/proto/parse-options.js index 706a466..d773cad 100644 --- a/lib/proto/parse-options.js +++ b/lib/proto/parse-options.js @@ -23,6 +23,7 @@ module.exports = function(options){ this.options.scrollTo = (typeof this.options.scrollTo === 'undefined') ? 0 : this.options.scrollTo; this.options.cacheBust = (typeof this.options.cacheBust === 'undefined') ? true : this.options.cacheBust this.options.debug = this.options.debug || false + this.options.timeout = this.options.timeout || 0 // we can’t replace body.outerHTML or head.outerHTML // it create a bug where new body or new head are created in the dom @@ -37,4 +38,4 @@ module.exports = function(options){ if (typeof options.analytics !== "function") { options.analytics = function() {} } -} \ No newline at end of file +} diff --git a/lib/request.js b/lib/request.js index 2054b6d..299a136 100644 --- a/lib/request.js +++ b/lib/request.js @@ -15,12 +15,17 @@ module.exports = function(location, options, callback) { } } + request.ontimeout = function() { + callback(null, request) + } + // Add a timestamp as part of the query string if cache busting is enabled if (this.options.cacheBust) { location += (!/[?&]/.test(location) ? "?" : "&") + new Date().getTime() } request.open(requestMethod.toUpperCase(), location, true) + request.timeout = options.timeout request.setRequestHeader("X-Requested-With", "XMLHttpRequest") request.setRequestHeader("X-PJAX", "true")