Skip to content

Instantly share code, notes, and snippets.

@influxweb
Forked from jnrbsn/gist:4268258
Last active April 19, 2017 18:19
Show Gist options
  • Save influxweb/b40d9b2f1f434485a8495b140575d80b to your computer and use it in GitHub Desktop.
Save influxweb/b40d9b2f1f434485a8495b140575d80b to your computer and use it in GitHub Desktop.
Loads a JavaScript file asynchronously with a callback, like jQuery's `$.getScript()` except without jQuery.
function loadScript(url, callback) {
var head = document.getElementsByTagName('head')[0],
scriptCalled = document.createElement('script');
scriptCalled.async = true;
scriptCalled.src = url;
scriptCalled.onload = scriptCalled.onreadystatechange = function () {
if (!scriptCalled.readyState || /loaded|complete/.test(scriptCalled.readyState)) {
scriptCalled.onload = scriptCalled.onreadystatechange = null;
if (head && scriptCalled.parentNode) {
head.removeChild(scriptCalled)
}
scriptCalled = undefined;
if (callback) {
callback();
}
}
};
//head.insertBefore(scriptCalled, head.firstChild);
head.appendChild(scriptCalled)
}
/**
* EXAMPLE:
*
loadScript('script_file.js', function () {
...DO SOMETHING...
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment