Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active December 9, 2016 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinweber/e7798b12fa26d99eea248c809e0eebb3 to your computer and use it in GitHub Desktop.
Save kevinweber/e7798b12fa26d99eea248c809e0eebb3 to your computer and use it in GitHub Desktop.
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