Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AJAX Javascript loader for poor connections
/*
[License]
MIT
[Purpose]
Also lets you verify the result content is valid or else it keeps retrying.
[Sample Usage]
getJsWithRetries("path/to/some.js", resp => resp.length === 100)
.then(() => {
console.success(`Succeeded`);
})
.catch(() => {
console.error(`Failed`);
});
*/
function getJsWithRetries(url, isValidFn,
{
retryTimes = 10,
onRetry = () => { }
}) {
return new Promise(function (resolve, reject) {
$.ajax({
method: "GET",
url: url,
cache: false
})
.done(onAjaxDone)
.error(onAjaxError);
function onAjaxDone(resp) {
if (isValidFn(resp)) {
appendAsScript(resp);
resolve();
} else {
var safeOffset = Math.min(5000, resp.length);
retryAjax(resp ? `${resp.length}B response length: ${resp.substring(0, safeOffset)}` : null);
}
}
function onAjaxError(xhr, status, error) {
retryAjax(`code: '${xhr.status}' error: '${error}' status: '${status}'`);
}
function appendAsScript(text) {
const script = document.createElement('script');
script.type = "text/javascript";
const scriptContent = document.createTextNode(text);
script.appendChild(scriptContent);
}
function retryAjax(reason) {
if (retryTimes === 0) {
reject();
return;
}
onRetry(retryTimes, reason);
retryTimes--;
getJsWithRetries(url, isValidFn, { retryTimes, onRetry })
.then(resolve)
.catch(reject);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment