influxweb
4/19/2017 - 6:14 PM

Loads a JavaScript file asynchronously with a callback, like jQuery's `$.getScript()` except without jQuery.

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...
	});
 */