Skip to content

Instantly share code, notes, and snippets.

@bytespider
Created March 27, 2011 20:10
Show Gist options
  • Save bytespider/889559 to your computer and use it in GitHub Desktop.
Save bytespider/889559 to your computer and use it in GitHub Desktop.
Require functions in external scripts on demand
/**
* demand.js
* @author: Rob Griffiths
* On demand javascript
*
* Usage:
* demand('alerter', 'alerter.js');
* ...
* alerter('OMG!'); // script is only inserted now and executed
*
*/
(function () {
var window = this;
var document = window.document;
function demand(functionName, filename) {
if (!(functionName in window && filename in included)) {
window[functionName] = function () {
var arg = arguments;
var script = require(filename);
script.onload = function () {
window[functionName].apply(this, arg);
};
}
}
}
var included = [];
function require(filename) {
if (filename in included) {
return included[filename];
}
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', filename);
included[filename] = script;
document.getElementsByTagName('HEAD')[0].appendChild(script);
return included[filename];
}
window['demand'] = demand;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment