Skip to content

Instantly share code, notes, and snippets.

@danielt69
Created August 5, 2018 09:03
Show Gist options
  • Select an option

  • Save danielt69/eb3bd410c1034b2d968adda8fdbac31f to your computer and use it in GitHub Desktop.

Select an option

Save danielt69/eb3bd410c1034b2d968adda8fdbac31f to your computer and use it in GitHub Desktop.
function getScript(url, callback, timeout) {
var timeoutIdx,
s = document.createElement('script');
s.type = 'text/' + (url.type || 'javascript');
s.src = url.src || url;
s.async = false;
s.onreadystatechange = s.onload = function() {
// this code handles two scenarios, whether called by onload or onreadystatechange
var state = s.readyState;
clearTimeout(timeoutIdx);
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
s.onreadystatechange = s.onload = null;
}
};
document.body.appendChild(s);
// You can't catch JSONP Errors, because it's handled by the script tag
// one way is to use a timeout
timeoutIdx = setTimeout(function() {
callback.done = true;
callback();
s.onreadystatechange = s.onload = null;
}, timeout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment