The main difference between usage in browsers and Node is in initially loading.
// Nodevar contextLoader = require('context-loader');// Browser<script src="context-loader.js"></script><script>var contextLoader = exports['context-loader']</script>
The global object also works
var context = contextLoader;
Script loading can be done in three ways.
// asynchronouscontextLoader;// synchronousvar compiledScript = contextLoader;if compiledScript /*...*/// raw codevar compiledScript = contextLoader;if compiledScript /*...*/
If loaded synchronously any errors will be passed back as the result
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.
// run using the current global contextcompiledScript;// run scripts and code in various waysvar executionOutcome = compiledScript;var executionOutcome = context;var executionOutcome = context;
Execution outcome is one of:
// using script.runInContext(context)context: object ExecutionContext // either the provided or newly initialized wrapped contextresult: returnValue // completion value of the executed code, if any// using context.run(scriptOrCode)script: object CompiledScript // either the provided CompiledScript or newly created script wrapper if code was passedresult: returnValue // completion value of the executed code, if any
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.
// "clone" a context organically by replaying all the code run in it in a new contextvar newContext = contextLoader;existingContexthistory;