This is an archived page. It's not actively maintained.


This article covers features introduced in SpiderMonkey 31

Compile a script off thread for execution.


JS::CanCompileOffThread(JSContext *cx, const JS::ReadOnlyCompileOptions &options,
                        size_t length);

JS::CompileOffThread(JSContext *cx, const JS::ReadOnlyCompileOptions &options,
                     const char16_t *chars, size_t length,
                     JS::OffThreadCompileCallback callback, void *callbackData);

JSScript *
JS::FinishOffThreadScript(JSContext *maybecx, JSRuntime *rt, void *token);

typedef void
(*JS::OffThreadCompileCallback)(void *token, void *callbackData);
Name Type Description
cx / maybe JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext.
rt JSRuntime * Pointer to a JS runtime.
options JS::ReadOnlyCompileOptions & Compile options.
chars const char16_t * String containing the script to compile.
length size_t The length of chars or bytes, in characters.
callback JS::OffThreadCompileCallback A callback function invoked when the compilation.
callbackData / token void * Pointer to application-defined data.


JS::CompileOffThread compiles a script, chars for execution.

The script is associated with a JS object. chars is the string containing the text of the script. length indicates the size of the text version of the script in characters.

After successfully triggering an off thread compile of a script, the callback will eventually be invoked with the specified data and a token for the compilation. The callback will be invoked while off the main thread, so its operations must be thread safe. Afterwards, JS::FinishOffThreadScript must be invoked on the main thread to get the result script or nullptr. If maybecx is not specified, the resources will be freed, but no script will be returned.

The characters passed in to JS::CompileOffThread must remain live until the callback is invoked, and the resulting script will be rooted until the call to FinishOffThreadScript.

See Also