Last active
August 18, 2017 04:53
-
-
Save dotjosh/48038477ad49e086854366677c7abab2 to your computer and use it in GitHub Desktop.
AJAX Javascript loader for poor connections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
[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