Context Loader
Create execution contexts, load JavaScript files, compile scripts without running them, run them as many times as you want in as many contexts as you want. Do it in Node or in the browser, with either asynchronous or synchronous loading.
Usage
First. Load context-loader
The main difference between usage in browsers and Node is in initially loading.
// Node
var contextLoader = require('context-loader');
// Browser
<script src="context-loader.js"></script>
<script>var contextLoader = exports['context-loader']</script>
Second. create a context
The global object also works
var context = contextLoader.createContext('myContext');
Third. load scripts with context-loader
Script loading can be done in three ways.
contextLoader.loadScript('path/filename.js', function callback(error, compiledScript){
if (compiledScript) { }
});
var compiledScript = contextLoader.loadScript('path/filename.js');
if (compiledScript) { }
var compiledScript = contextLoader.wrap('(function(){ return "I am compiled code" })()');
if (compiledScript) { }
If loaded synchronously any errors will be passed back as the result
Fourth. Run code in contexts
Once you have the compiled script you can then run it in contexts. State isn't shared inside the script itself so it can be used multiple times in the same or different contexts. In Node, a context is either the global object or a Context object created using the vm module. In the browser a context is either the global object or some other window object like an iframe contentWindow.
compiledScript.runInContext();
var executionOutcome = compiledScript.runInContext(context);
var executionOutcome = context.run(compiledScript);
var executionOutcome = context.run('x = {}');
Execution outcome is one of:
{ context: [object ExecutionContext],
result: returnValue }
{ script: [object CompiledScript],
result: returnValue }
Execution History
Every time a script is run there is a record created on both the script and the context. Each piece of code is wrapped in a CompiledScript object with a history record, and every context is wrapped in an ExecutionContext object also with a history.
The history allows you to easily replay a series of code executions in the same order, or to cross-reference which contexts have had what code run in them.
var newContext = contextLoader.createContext();
existingContext.history.forEach(function(outcome){
newContext.run(outcome.script);
});