I’m wondering what would be the simplest method, using JavaScript, to check if the origin server is accessible and available to process Ajax requests? To provide more context: there are pages on this site, built in WordPress, that provide filterable lists of posts, and each interaction with a filter sends an Ajax request. The site is configured with an edge cache such that if the origin goes down, visitors would still access a cached version of the page. If, however, a visitor is viewing a cached page under these circumstances, the filters will not work, as Ajax requests to the origin will fail. Essentially, I would like a way to detect if a visitor is, in fact, viewing a static version of the page served by the edge cache and, if so, append a class to the <body>
of the document.
I’m wondering if it would suffice to simply create an XMLHttpRequest
instance and check its response in a manner such as the following, or is there a more reliable and/or efficient approach?
const xhr = new XMLHttpRequest();
// open request to primary site domain
xhr.open('GET', 'https://example.com');
// check for response and apply class if origin is unavailable
xhr.onload = function() {
if (xhr.status === 200) {
// can perform Ajax requests and origin is available
} else {
// cannot perform Ajax requests, thus origin must not be available
document.body.classList.add("no-origin");
}
};
2
Answers
Here’s all you need to check for accessibility…
Apologies… you made me feel bad so here’s an alternative solution:
Checking for the accessibility of a small server resource: