Created
March 27, 2011 20:10
-
-
Save bytespider/889559 to your computer and use it in GitHub Desktop.
Require functions in external scripts on demand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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