Skip to content

Instantly share code, notes, and snippets.

@lira
Forked from colingourlay/LICENSE
Created January 5, 2021 19:43
Show Gist options
  • Save lira/40d9b304740121a9e4ae3b79d06303c1 to your computer and use it in GitHub Desktop.
Save lira/40d9b304740121a9e4ae3b79d06303c1 to your computer and use it in GitHub Desktop.
Standalone getScript. This performs the same ability as jQuery.getScript, including the optional callback, but doesn't support the Promises implementation shared with all the other jQuery.ajax methods.
/**
* Fetches and inserts a script into the page before the first
* pre-existing script element, and optionally calls a callback
* on completion.
*
* [TODO] Make this a module of its own so it can be used elsewhere.
*
* @param {String} src source of the script
* @param {Function} callback (optional) onload callback
*/
var getScript = function (src, callback) {
var el = document.createElement('script');
el.type = 'text/javascript';
el.async = false;
el.src = src;
/**
* Ensures callbacks work on older browsers by continuously
* checking the readyState of the request. This is defined once
* and reused on subsequent calls to getScript.
*
* @param {Element} el script element
* @param {Function} callback onload callback
*/
getScript.ieCallback = getScript.ieCallback || function (el, callback) {
if (el.readyState === 'loaded' || el.readyState === 'complete') {
callback();
} else {
setTimeout(function () { getScript.ieCallback(el, callback); }, 100);
}
};
if (typeof callback === 'function') {
if (typeof el.addEventListener !== 'undefined') {
el.addEventListener('load', callback, false);
} else {
el.onreadystatechange = function () {
el.onreadystatechange = null;
getScript.ieCallback(el, callback);
};
}
}
// This is defined once and reused on subsequeent calls to getScript
getScript.firstScriptEl = getScript.firstScriptEl || document.getElementsByTagName('script')[0];
getScript.firstScriptEl.parentNode.insertBefore(el, getScript.firstScriptEl);
};
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment