Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helper: Check target URL using XMLHttpRequest before we execute a callback accordingly. No Ajax/Promise needed.
/**
* Ensure that target page exists before we actually do something.
*
* @param {string} targetUrl - Absolute target URL to be tested
* @param {function} [successCallback] - Function to be executed on success
* @param {function} [failCallback] - Function to be executed on fail
*/
function checkTargetFirst(targetUrl, successCallback, failCallback) {
var reader = new XMLHttpRequest();
successCallback = successCallback || function () {};
failCallback = failCallback || function () {};
//// For debugging: You override targetUrl here and play arround
//// by commenting out the success and fail callback.
// targetUrl = "http://localhost:4502/content/client-site/ch_CH.html";
reader.open('get', targetUrl, true);
reader.onreadystatechange = function () {
if (reader.readyState === 4) {
// Check whether request for the file failed or succeeded
if ((reader.status === 200) || (reader.status === 0)) {
successCallback();
} else {
failCallback();
}
}
};
reader.send(null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.