javascript: URLs.
* Event handlers, whether registered through the DOM using addEventListener(), by
explicit event handler content attributes, by event handler IDL attributes, or
otherwise.
* Processing of technologies like SVG that have their own scripting features.
Since this exception value is provided by the JavaScript specification, we know that it is never null, so we use null to signal that no error has occurred.
: Fetch options :: A set of script fetch options, containing various options related to fetching this script or module scripts that it imports. : A base URL :: A base URL used for resolving module specifiers when resolving a module specifier. This will either be the URL from which the script was obtained, for external module scripts, or the document base URL of the containing document, for inline module scripts. A classic script additionally has: : A muted errors boolean :: A boolean which, if true, means that error information will not be provided for errors in this script (used to mute errors for cross-origin scripts, since that can leak private information). A module script is another type of script. It has no additional items. An environment is an object that identifies the settings of a current or potential execution environment. An environment has the following fields: : An id :: An opaque string that uniquely identifies the environment. : A creation URL :: A URL record that represents the location of the resource with which the environment is associated.In the case of an environment settings object, this URL might be
distinct from the environment settings object's responsible document's URL, due to mechanisms such as
history.pushState().
When a script creates and navigates a new top-level browsing context, the {{Window/opener}} attribute of the new browsing context's {{Window}} object will be set to the responsible browsing context's {{WindowProxy}} object.
: A responsible event loop :: An event loop that is used when it would not be immediately clear what event loop to use. : A responsible document :: A {{Document}} that is assigned responsibility for actions taken by the scripts that use this environment settings object.For example, the [=Document/URL=] of the responsible document is used to set the [=Document/URL=] of the {{Document}} after it has been reset using {{Document/open()}}.
If the responsible event loop is not a browsing context event loop, then the environment settings object has no responsible document. : An API URL character encoding :: A character encoding used to encode URLs by APIs called by scripts that use this environment settings object. : An API base URL :: An [=url/URL=] used by APIs called by scripts that use this environment settings object to parse URLs. : An origin :: An [=concept/origin=] used in security checks. : An HTTPS state :: An HTTPS state value representing the security properties of the network channel used to deliver the resource with which the environment settings object is associated. : An referrer policy :: The default referrer policy for fetches performed using this environment settings object as a request client. [[!REFERRERPOLICY]] An environment settings object also has an outstanding rejected promises weak set and an about-to-be-notified rejected promises list, used to track unhandled promise rejections. The outstanding rejected promises weak set must not create strong references to any of its members, and implementations are free to limit its size, e.g., by removing old entries from it when new ones are added.This section introduces a number of algorithms for fetching scripts, taking various necessary inputs and resulting in classic scripts or module scripts.
Script fetch options is a struct with the following items:
The cryptographic nonce metadata used for the initial fetch and for fetching any imported modules
The integrity metadata used for the initial fetch
The parser metadata used for the initial fetch and for fetching any imported modules
The credentials mode used for the initial fetch (for module scripts) and for fetching any imported modules (for both module scripts and classic scripts)
The [[!REFERRER-POLICY#referrer policy]] used for the initial fetch and for fetching any imported modules
Recall that via the import() feature, classic scripts can import module scripts.
The default classic script fetch options are a set of script fetch options
whose cryptographic nonce is the empty string, integrity metadata is the empty string,
parser metadata is "not-parser-inserted", credentials mode is "omit",
and referrer policy is the empty string.
Given a request request and script fetch options options, we define:
Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options' integrity metadata, its parser metadata to options' parser metadata, and its referrer policy to options' referrer policy.
Set request's cryptographic nonce metadata to options' cryptographic nonce, its integrity metadata to options' integrity metadata, its parser metadata to options' parser metadata, its credentials mode to options' credentials mode, and its referrer policy to options' referrer policy.
import statements encountered throughout the graph.
Service Workers is an example of a specification that runs these algorithms with its own options for the hooks. [[SERVICE-WORKERS]]
To fetch a classic script for a <{script}> element element, given a url, a CORS setting, a settings object, and some options, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success). 1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting. 2. Set request's client to object. 3. Set up the classic script request given request and options. 4. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set. Return from this algorithm, and when the custom perform the fetch steps complete with response response, run the remaining steps.Otherwise, fetch request.
5. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response.response can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.
6. If response's type is "error", or
response's status is not an ok status, asynchronously complete this
algorithm with null, and abort these steps.
7. If the caller specified custom steps to process the response, perform them on
response. If they return false, complete this algorithm with null, and abort these
steps.
8. If response's Content-Type metadata, if any, specifies a character encoding,
and the user agent supports that encoding, then set character encoding to that
encoding (ignoring the passed-in value).
9. Let source text be the result of decoding response's
[=response/body=] to Unicode, using character encoding as the fallback
encoding.
The decode algorithm overrides character encoding if the file contains a BOM.
10. Let script be the result of creating a classic script using source text and settings object. If response was CORS-cross-origin, then pass the muted errors flag to the create a classic script algorithm as well. 11. Asynchronously complete this algorithm with script. To fetch a classic worker script given a url, a fetch client settings object, a destination, and a script settings object, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success). 1. Let request be a new request whose url is url, client is fetch client settings object, destination is destination, mode is "same-origin", credentials mode is "same-origin",
parser metadata is "not parser-inserted", and whose
use-URL-credentials flag is set.
2. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set.
Return from this algorithm, and when the custom perform the fetch steps complete with response response,
run the remaining steps.
Otherwise, fetch request.
4. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response. 5. If response's type is "error", or
response's status is not an ok status, asynchronously complete this
algorithm with null, and abort these steps.
6. If the caller specified custom steps to process the response, perform them on
response. If they return false, complete this algorithm with null, and abort these
steps.
7. Let source text be the result of UTF-8 decoding response's
[=response/body=].
8. Let script be the result of creating a classic script using source
text and settings object.
9. Asynchronously complete this algorithm with script.
To fetch a module script tree
given a url, a settings object, a destination, and some
options, run these
steps. The algorithm will asynchronously complete with either null (on failure) or a new
module script (on success).
1. If ancestor list is not given, let it be an empty list.
2. If module map settings object is not given, let it be fetch client settings
object.
3. Fetch a single module script given url, credentials mode,
cryptographic nonce, parser state, destination, and
module map settings object. If the caller of this algorithm specified custom
set up the module script request or process the response steps, pass those along while
fetching a single module script.
4. Return from this algorithm and run the following steps when fetching a single module
script asynchronously completes with result:
5. If result is null, asynchronously complete this algorithm with null and abort these
steps.
6. Otherwise, result is a module script. Fetch the descendants of
result given destination and an ancestor list obtained by appending
url to ancestor list.
7. When fetching the descendants of a module script asynchronously completes with
descendants result, asynchronously complete this algorithm with descendants
result.
It is intentional that no custom set up the module script request or process the response steps are passed along here. Those hooks only apply to the top-level fetch at the root of the module script tree.
If any of the fetch a module script tree invocations asynchronously complete with null, the user agent may terminate any or all of the other fetches, and must then asynchronously complete this algorithm with null. Once all of the fetch a module script tree invocations asynchronously complete with a module script, asynchronously complete this algorithm with module script. To fetch a single module script, given a url, a fetch client settings object, a destination, some options, a module map settings object, a referrer, and a top-level module fetch flag, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success). 1. Let module map be settings object's module map. 2. If module map contains an entry with key url whose value is "fetching", wait (in parallel) until that entry's value changes, then
proceed to the next step.
3. If module map contains an entry with key url, asynchronously complete
this algorithm with that entry's value, and abort these steps.
4. Create an entry in module map with key url and value
"fetching".
5. Let request be a new request whose
url is url, destination is destination, mode is "cors",
referrer is referrer, and client is fetch client settings
object. Set up the module script request given request and
options.
6. If the caller specified custom steps to set up the module script request, perform them on
request.
7. Fetch request.
8. Return from this algorithm, and run the remaining steps as part of the fetch's
process response for the response response.
response is always CORS-same-origin.
9. If any of the following conditions are met, set the value of the entry in module map whose key is url to null, asynchronously complete this algorithm with null, and abort these steps: * response's type is "error"
* response's status is not an ok status
* The result of extracting a MIME type from response's
[=response/header list=] (ignoring parameters) is not a
JavaScript MIME type.
For historical reasons, fetching a classic script does not include MIME type checking. In contrast, module scripts will fail to load if they are not of a correct MIME type.
* The caller specified custom steps to process the response, which when performed on response return false. 10. Let source text be the result of UTF-8 decoding response's [=response/body=]. 11. Let module script be the result of creating a module script given source text, settings object, response's url, credentials mode, and cryptographic nonce. 12. Set the value of the entry in module map whose key is url to module script, and asynchronously complete this algorithm with module script.It is intentional that the module map is keyed by the request URL, whereas the base URL for the module script is set to the response URL. The former is used to deduplicate fetches, while the latter is used for URL resolution.
This step will recursively instantiate all of the module's dependencies.
5. If instantiationStatus is an abrupt completion, report the exception given by instantiationStatus.\[[Value]] for s and abort these steps. 6. Prepare to run script given settings. 7. Let evaluationStatus be record.ModuleEvaluation().This step will recursively evaluate all of the module's dependencies.
8. If evaluationStatus is an abrupt completion, report the exception given by evaluationStatus.\[[Value]] for s. (Do not perform this step if ScriptEvaluation fails to complete as a result of the user agent aborting the running script.) 9. Clean up after running script with settings. The steps to check if we can run script with an environment settings object settings are as follows. They return either "run" or "do not run". 1. If the global object specified by settings is a {{Window}} object whose {{Document}} object is not fully active, then return "do not run" and abort these steps. 2. If scripting is disabled for the responsible browsing context specified by settings, then return "do not run" and abort these steps. 3. Return "run". The steps to prepare to run script with an environment settings object settings are as follows: 1. Increment settings's realm execution context's entrance counter by one. 2. Push settings's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context. The steps to clean up after running script with an environment settings object settings are as follows: 1. Assert: settings's realm execution context is the running JavaScript execution context. 2. Decrement settings's realm execution context's entrance counter by one. 3. Remove settings's realm execution context from the JavaScript execution context stack. 4. If the JavaScript execution context stack is now empty, run the global script clean-up jobs. (These cannot run scripts.) 5. If the JavaScript execution context stack is now empty, perform a microtask checkpoint. (If this runs scripts, these algorithms will be invoked reentrantly.)These algorithms are not invoked by one script directly calling another, but they can be invoked reentrantly in an indirect manner, e.g., if a script dispatches an event which has event listeners registered.
The running script is the script in the \[[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context. Each unit of related similar-origin browsing contexts has a global script clean-up jobs list, which must initially be empty. A global script clean-up job cannot run scripts, and cannot be sensitive to the order in which other clean-up jobs are executed. The File API uses this to releaseblob: URLs. [[!FILEAPI]]
When the user agent is to run the global script clean-up jobs, the user agent must
perform each of the jobs in the global script clean-up jobs list and then empty the
list.
In this specification, all JavaScript realms are initialized with
global objects that are either {{Window}} or {{WorkerGlobalScope}} objects.
There is always a 1:1:1 mapping between JavaScript realms, global objects, and
environment settings objects:
* A JavaScript realm has a \[[HostDefined]] field, which contains the Realm's settings
object.
* A JavaScript realm has a \[[GlobalObject]] field, which contains the Realm's global
object.
* Each global object in this specification is created during the
initialization of a corresponding
JavaScript realm, known as the global object's Realm.
* Each global object in this specification is created alongside a corresponding
environment settings object, known as its relevant settings object.
* An environment settings object's realm execution context's Realm component is
the environment settings object's Realm.
* An environment settings object's Realm then has a \[[GlobalObject]] field, which
contains the environment settings object's global object.
When defining algorithm steps throughout this specification, it is often important to indicate
what JavaScript realm is to be used—or, equivalently, what global object or
environment settings object is to be used. In general, there are at least four
possibilities:
: Entry
:: This corresponds to the script that initiated the currently running script action: i.e., the
function or script that the user agent called into when it called into author code.
: Incumbent
:: This corresponds to the most-recently-entered author function or script on the stack.
: Current
:: This corresponds to the currently-running function object, including built-in user-agent
functions which might not be implemented as JavaScript. (It is derived from the current
JavaScript realm.)
: Relevant
:: Every platform object has a relevant Realm. When writing algorithms, the most
prominent platform object whose relevant Realm might be important is the
this value of the currently-running function object. In some cases, there can be
other important relevant Realms, such as those of any arguments.
Note how the entry, incumbent, and current concepts are usable without
qualification, whereas the relevant concept must be applied to a particular
platform object.
a.html being loaded in a browser window,
b.html being loaded in an <{iframe}> as shown, and c.html and
d.html omitted (they can simply be empty documents):
a.html, then:
* The entry Realm is that of a.html.
* The incumbent Realm is that of b.html.
* The current Realm is that of c.html (since it is the {{Window/print()}}
method from c.html whose code is running).
* The relevant Realm of the object on which the {{Window/print()}} method is being called
is that of d.html.
The incumbent and entry concepts should not be used by new specifications, and we are considering whether we can remove almost all existing uses
Currently, the incumbent concept is used in some security checks, and the entry concept is sometimes used to obtain, amongst other things, the API base URL to parse a URL, used in scripts running in that unit of related similar-origin browsing contexts. In general, the current concept is what should be used by specifications going forward. There is an important exception, however. If an algorithm is creating an object that is to be persisted and returned multiple times (instead of simply returned to author code right away, and never vended again), it should use the relevant concept with regard to the object on which the method in question is being executed. This prevents cross-realm calls from causing an object to store objects created in the "wrong" realm.
navigator.getBattery() method creates promises in the relevant Realm for
the {{Navigator}} object on which it is invoked. This has the following impact: [[BATTERY-STATUS]]
getBattery() method had instead used the current
Realm, all the results would be reversed. That is, after the first call to
getBattery() in outer.html, the {{Navigator}} object in
inner.html would be permanently storing a {{Promise}} object created in
outer.html's JavaScript realm, and calls like that inside the
hello() function would thus return a promise from the "wrong" realm. Since this is
undesirable, the algorithm instead uses the relevant Realm, giving the sensible results
indicated in the comments above.
The "global environment associated with" concept is from the olden days, before the modern JavaScript specification and its concept of realms. We expect that as the Web IDL specification gets updated, every platform object will have a Realm associated with it, and this definition can be re-cast in those terms. [[ECMA-262]] [[WEBIDL]]
finally blocks. [[ECMA-262]]
User agents may impose resource limitations on scripts, for example CPU quotas, memory limits,
total execution time limits, or bandwidth limitations. When a script exceeds a limit, the user
agent may either throw a {{QuotaExceededError}} exception, abort the script without an
exception, prompt the user, or throttle script execution.
For example, the prompt mentioned in the example above could also offer the
user with a mechanism to just close the page entirely, without running any unload
event handlers.
This is not strictly true. It is in fact possible, by taking liberal advantage of the many "implementation defined" sections of the algorithm, to contort it to our purposes. However, the end result is a mass of messy indirection and workarounds that essentially bypasses the job queue infrastructure entirely, albeit in a way that is technically sanctioned within the bounds of implementation-defined behavior. We do not take this path, and instead introduce the following willful violation.
As such, user agents must instead use the following definition in place of that in the JavaScript specification. These ensure that the promise jobs enqueued by the JavaScript specification are properly integrated into the user agent's event loops."PromiseJobs". ("ScriptJobs" must not
be used by user agents.)
2. Let settings be the settings object of job.\[[Realm]]
3. Queue a microtask, on settings's responsible event loop, to perform
the following steps:
1. Check if we can run script with settings. If this returns "do not run"
then abort these steps.
2. Prepare to run script with settings.
3. Let result be the result of performing the abstract operation specified by
job, using the elements of arguments as its arguments.
4. Clean up after running script with settings.
5. If result is an abrupt completion, report the exception given by
result.\[[Value]].
module", and how modules are fetched, resolved, and executed. [[ECMA-262]]
Although the JavaScript specification speaks in terms of "scripts" versus "modules", in general this specification speaks in terms of classic scripts versus module scripts, since both of them use the <{script}> element.
A module map is a map of absolute URLs to values that are either a module script, null, or a placeholder value "fetching". Module maps are used to
ensure that imported JavaScript modules are only fetched, parsed, and evaluated once per
{{Document}} or {{Worker}}.
To resolve a module specifier
given a module script script and a string specifier, perform the
following steps. It will return either an absolute URL or failure.
1. Apply the URL parser to specifier. If the result is not failure, return the
result.
2. If specifier does not start with the character U+002F SOLIDUS (/), the two-character
sequence U+002E FULL STOP, U+002F SOLIDUS (./), or the three-character sequence
U+002E FULL STOP, U+002E FULL STOP, U+002F SOLIDUS (../), return failure and abort these
steps.
This restriction is in place so that in the future we can allow custom module
loaders to give special meaning to "bare" import specifiers, like import "jquery"
or import "web/crypto". For now any such imports will fail, instead of being
treated as relative URLs.
fetching", throw a {{TypeError}} exception and abort these steps.
5. Return resolved module script's module record.
The resource containing the script will typically be the file from which the {{Document}} was parsed, e.g., for inline <{script}> elements or event handler content attributes; or the JavaScript file that the script was in, for external scripts. Even for dynamically-generated scripts, user agents are strongly encouraged to attempt to keep track of the original source of a script. For example, if an external script uses the {{Document/write()|document.write()}} API to insert an inline <{script}> element during parsing, the URL of the resource containing the script would ideally be reported as being the external script, and the line number might ideally be reported as the line with the {{Document/write()|document.write()}} call or where the string passed to that call was first constructed. Naturally, implementing this can be somewhat non-trivial.
User agents are similarly encouraged to keep careful track of the original line numbers, even in the face of {{Document/write()|document.write()}} calls mutating the document as it is parsed, or event handler content attributes spanning multiple lines.
6. If script has muted errors, then set message to "Script error.", set location to the empty string, set line
and col to 0, and set error object to null.
7. Let event be a new trusted {{ErrorEvent}} object that does not bubble but is
cancelable, and which has the event name error.
8. Initialize event's {{ErrorEvent/message}} attribute to message.
9. Initialize event's {{ErrorEvent/filename}} attribute to location.
10. Initialize event's {{ErrorEvent/lineno}} attribute to line.
11. Initialize event's {{ErrorEvent/colno}} attribute to col.
12. Initialize event's {{ErrorEvent/error}} attribute to error object.
13. Dispatch event at target.
14. Let target no longer be in error reporting mode.
15. If event was canceled, then the error is handled. Otherwise,
the error is not handled.
Returning true cancels event per the event handler processing algorithm.
ErrorEvent interface
[Constructor(DOMString type, optional ErrorEventInit eventInitDict), Exposed=(Window, Worker)]
interface ErrorEvent : Event {
readonly attribute DOMString message;
readonly attribute DOMString filename;
readonly attribute unsigned long lineno;
readonly attribute unsigned long colno;
readonly attribute any error;
};
dictionary ErrorEventInit : EventInit {
DOMString message = "";
DOMString filename = "";
unsigned long lineno = 0;
unsigned long colno = 0;
any error = null;
};
The message attribute must return the value it
was initialized to. It represents the error message.
The filename attribute must return the value it
was initialized to. It represents the absolute URL of the script in which the error
originally occurred.
The lineno attribute must return the value it
was initialized to. It represents the line number where the error occurred in the script.
The colno attribute must return the value it
was initialized to. It represents the column number where the error occurred in the script.
The error attribute must return the value it
was initialized to. Where appropriate, it is set to the object representing the error
(e.g., the exception object in the case of an uncaught DOM exception).
unhandledrejection and
rejectionhandled events.
When the user agent is to notify about rejected promises on a given environment
settings object settings object, it must run these steps:
1. Let list be a copy of settings object's about-to-be-notified
rejected promises list.
2. If list is empty, abort these steps.
3. Clear settings object's about-to-be-notified rejected promises list.
4. Queue a task to run the following substep:
1. For each promise p in list:
1. If p's \[[PromiseIsHandled]] internal slot is true, continue to the next
iteration of the loop.
2. Let event be a new trusted PromiseRejectionEvent object
that does not bubble but is cancelable, and which has the event name
unhandledrejection.
3. Initialise event's {{PromiseRejectionEvent/promise}} attribute to
p.
4. Initialise event's {{PromiseRejectionEvent/reason}} attribute to the value
of p's \[[PromiseResult]] internal slot.
5. Dispatch event at settings object's global object.
6. If the event was canceled, then the promise rejection is handled.
Otherwise, the promise rejection is not handled.
7. If p's \[[PromiseIsHandled]] internal slot is false, add p to
settings object's outstanding rejected promises weak set.
This algorithm results in promise rejections being marked as handled or
not handled. These concepts parallel handled and
not handled script errors. If a rejection is still
not handled after this, then the rejection may be reported to a developer
console.
"reject",
1. Add promise to settings object's about-to-be-notified
rejected promises list.
5. If operation is "handle",
1. If settings object's about-to-be-notified rejected promises list contains
promise, remove promise from that list and abort these steps.
2. If settings object's outstanding rejected promises weak set does not
contain promise, abort these steps.
3. Remove promise from settings object's outstanding rejected
promises weak set.
4. Queue a task to run the following steps:
1. Let event be a new trusted {{PromiseRejectionEvent}} object that does
not bubble and is not cancelable, and which has the event name
rejectionhandled.
2. Initialise event's {{PromiseRejectionEvent/promise}} attribute to
promise.
3. Initialise event's {{PromiseRejectionEvent/reason}} attribute to the value
of promise's \[[PromiseResult]] internal slot.
4. Dispatch event at settings object's global object.
PromiseRejectionEvent interface
[Constructor(DOMString type, PromiseRejectionEventInit eventInitDict), Exposed=(Window,Worker)]
interface PromiseRejectionEvent : Event {
readonly attribute Promise<any> promise;
readonly attribute any reason;
};
dictionary PromiseRejectionEventInit : EventInit {
required Promise<any> promise;
any reason;
};
The promise attribute must return
the value it was initialized to. It represents the promise which this notification is about.
The reason attribute must return
the value it was initialized to. It represents the rejection reason for the promise.
When there is more than one event loop for a unit of related browsing contexts, complications arise when a browsing context in that group is navigated such that it switches from one unit of related similar-origin browsing contexts to another. This specification does not currently describe how to handle these complications.
A browsing context event loop always has at least one browsing context. If such an event loop's browsing contexts all go away, then the event loop goes away as well. A browsing context always has an event loop coordinating its activities. Worker event loops are simpler: each worker has one event loop, and the worker processing model manages the event loop's lifetime.Not all events are dispatched using the task queue, many are dispatched during other tasks.
: Parsing :: The HTML parser tokenizing one or more bytes, and then processing any resulting tokens, is typically a task. : Callbacks :: Calling a callback is often done by a dedicated task. : Using a resource :: When an algorithm fetches a resource, if the fetching occurs in a non-blocking fashion then the processing of the resource once some or all of the resource is available is performed by a task. : Reacting to DOM manipulation :: Some elements have tasks that trigger in response to DOM manipulation, e.g., when that element is inserted into the document. Each task in a browsing context event loop is associated with a {{Document}}; if the task was queued in the context of an element, then it is the element's node document; if the task was queued in the context of a browsing context, then it is the browsing context's active document at the time the task was queued; if the task was queued by or for a [=concept/script=] then the document is the responsible document specified by the script's settings object. A task is intended for a specific event loop: the event loop that is handling tasks for the task's associated {{Document}} or {{Worker}}. When a user agent is to queue a task, it must add the given task to one of the task queues of the relevant event loop. Each task is defined as coming from a specific task source. All the tasks from one particular task source and destined to a particular event loop (e.g., the callbacks generated by timers of a {{Document}}, the events fired for mouse movements over that {{Document}}, the tasks queued for the parser of thatDocument) must always be added
to the same task queue, but tasks from different task sources may be placed
in different task queues.
For example, a user agent could have one task queue for mouse and key events (the user interaction task source), and another for everything else. The user agent could then give keyboard and mouse events preference over other tasks three quarters of the time, keeping the interface responsive but not starving other task queues, and never processing events from any one task source out of order.
Each event loop has a currently running task. Initially, this is null. It is used to handle reentrancy. Each event loop also has a performing a microtask checkpoint flag, which must initially be false. It is used to prevent reentrant invocation of the perform a microtask checkpoint algorithm.There are many factors that affect the ideal update frequency for the top-level browsing context including performance, power, background operation, quality of user experience, refresh rate of display(s), etc. When in foreground and not constrained by resources (i.e. performance, battery versus mains power, other resource limits), the user agent normally prioritizes for maximum quality of user experience for that set of {{Document}}s by matching update frequency and animation frame callback rate to the current refresh rate of the current display (usually 60Hz, but refresh rate may be higher or lower). When accommodating constraints on resources, the update frequency might automatically run at a lower rate. Also, if a top-level browsing context is in the background, the user agent might decide to drop that page to a much slower 4Hz, or even less.
Another example of why a browser might skip updating the rendering is to ensure certain tasks are executed immediately after each other, with only microtask checkpoints interleaved (and without, e.g., animation frame callbacks interleaved). For example, a user agent might wish to coalesce callbacks together, with no intermediate rendering updates. However, when are no constraints on resources, there must not be an arbitrary permanent user agent limit on the update rate and animation frame callback rate (i.e., high refresh rate displays and/or low latency applications).
4. If there are a nested browsing contexts B that the user agent believes would not benefit from having their rendering updated at this time, then remove from docs all {{Document}} objects whose browsing context is in B.As with top-level browsing contexts, a variety of factors can influence whether it is profitable for a browser to update the rendering of nested browsing contexts. For example, a user agent might wish to spend less resources rendering third-party content, especially if it is not currently visible to the user or if resources are constrained. In such cases, the browser could decide to update the rendering for such content infrequently or never.
5. For each fully active {{Document}} in docs, run the resize steps for that {{Document}}, passing in now as the timestamp. [[!CSSOM-VIEW]] 6. For each fully active {{Document}} in docs, run the scroll steps for that {{Document}}, passing in now as the timestamp. [[!CSSOM-VIEW]] 7. For each fully active {{Document}} in docs, evaluate media queries and report changes for that {{Document}}, passing in now as the timestamp. [[!CSSOM-VIEW]] 8. For each fully active {{Document}} in docs, run CSS animations and send events for that {{Document}}, passing in now as the timestamp. [[CSS3-ANIMATIONS]] 9. For each fully active {{Document}} in docs, run the fullscreen rendering steps for that {{Document}}, passing in now as the timestamp. [[!FULLSCREEN]] 10. For each fully active {{Document}} in docs, run the animation frame callbacks for that {{Document}}, passing in now as the timestamp. 12. For each fully active {{Document}} in docs, update the rendering or user interface of that {{Document}} and its browsing context to reflect the current state. 8. If this is a {{Worker}} event loop (i.e., one running for a {{WorkerGlobalScope}}), but there are no tasks in the event loop's task queues and the {{WorkerGlobalScope}} object's closing flag is true, then destroy the event loop, aborting these steps, resuming the run a worker steps. 9. Return to the first step of the event loop.This specification only has solitary callback microtasks. Specifications that use compound microtasks have to take extra care to wrap callbacks to handle spinning the event loop.
When an algorithm requires a microtask to be queued, it must be appended to the relevant event loop's microtask queue; the task source of such a microtask is the microtask task source.It is possible for a microtask to be moved to a regular task queue, if, during its initial execution, it spins the event loop. In that case, the microtask task source is the task source used. Normally, the task source of a microtask is irrelevant.
When a user agent is to perform a microtask checkpoint, if the performing a microtask checkpoint flag is false, then the user agent must run the following steps: 1. Let the performing a microtask checkpoint flag be true. 2. Microtask queue handling: If the event loop's microtask queue is empty, jump to the Done step below. 3. Select the oldest microtask on the event loop's microtask queue. 4. Set the event loop's currently running task to the task selected in the previous step. 5. Run: Run the selected task.This might involve invoking scripted callbacks, which eventually calls the clean up after running script steps, which call this perform a microtask checkpoint algorithm again, which is why we use the performing a microtask checkpoint flag to avoid reentrancy.
6. Set the event loop's currently running task back to null. 7. Remove the microtask run in the step above from the microtask queue, and return to the Microtask queue handling step. 8. Done: For each environment settings object whose responsible event loop is this event loop, notify about rejected promises on that environment settings object. 9. Cleanup Indexed Database transactions. 10. Let the performing a microtask checkpoint flag be false. If, while a compound microtask is running, the user agent is required to execute a compound microtask subtask to run a series of steps, the user agent must run the following steps: 1. Let parent be the event loop's currently running task (the currently running compound microtask). 2. Let subtask be a new task that consists of running the given series of steps. The task source of such a microtask is the microtask task source. This is a compound microtask subtask. 3. Set the event loop's currently running task to subtask. 4. Run subtask. 5. Set the event loop's currently running task back to parent.Steps in synchronous sections are marked with ⌛.
This might be a microtask, in which case it is a solitary callback microtask. It could also be a compound microtask subtask, or a regular task that is not a microtask. It will not be a compound microtask.
2. Let task source be task's task source. 3. Let old stack be a copy of the JavaScript execution context stack. 4. Empty the JavaScript execution context stack. 5. Run the global script clean-up jobs. 6. Perform a microtask checkpoint. 7. Stop task, allowing whatever algorithm that invoked it to resume, but continue these steps in parallel.This causes one of the following algorithms to continue: the event loop's main set of steps, the perform a microtask checkpoint algorithm, or the execute a compound microtask subtask algorithm to continue.
8. Wait until the condition goal is met. 9. Queue a task to continue running these steps, using the task source task source. Wait until this new task runs before continuing these steps. 10. Replace the JavaScript execution context stack with the old stack. 11. Return to the caller.click events) must be fired using
tasks queued with the user interaction task source. [[!UIEVENTS]]
: The networking task source
:: This task source is used for features that trigger in response to network activity.
: The history traversal task source
:: This task source is used to queue calls to {{History/back()|history.back()}} and
similar APIs.
on" and is followed by the name of the event for which it is intended.
An event handler has a value, which is either null, or is a callback object, or is an
internal raw uncompiled handler. The {{EventHandler}} callback function type describes how
this is exposed to scripts. Initially, an event handler's value must be set to null.
Event handlers are exposed in one of two ways.
The first way, common to all event handlers, is as an event handler IDL attribute.
The second way is as an event handler content attribute. Event handlers on
HTML elements and some of the event handlers on {{Window}} objects are exposed in this way.
This can happen in particular for event handler IDL attribute on <{body}> elements that do not have corresponding {{Window}} objects.
Certain event handler IDL attributes have additional requirements, in particular
the onmessage attribute of {{MessagePort}} objects.
Blocked" when executed upon the attribute's element
"script attribute", and the attribute's value, then abort these steps. [[!CSP3]]
2. Set the corresponding event handler to an internal raw uncompiled handler
consisting of the attribute's new value and the script location where the attribute was set to
this value.
When an event handler content attribute is removed, the user agent must set the
corresponding event handler to null.
The callback is emphatically not the event handler itself. Every event handler ends up registering the same callback the algorithm defined below, which takes care of invoking the right callback, and processing the callback's return value.
This only happens the first time the event
handler's value is set. Since listeners are called in the order they were registered, the
order of event listeners for a particular event type will always be first the event listeners
registered with addEventListener() before
the first time the event handler was set to a non-null value,
then the callback to which it is currently set, if any, and finally the event listeners registered
with addEventListener() after the
first time the event handler was set to a non-null value.
The interfaces implemented by the event object do not influence whether an event handler is triggered or not.
The event handler processing algorithm for an event handler H and an {{Event}} object E is as follows: 1. Let callback be the result of getting the current value of the event handler H. 2. If callback is null, then abort these steps. 3. Process the {{Event}} object E as follows:OnErrorEventHandlermouseovererror and E is an {{ErrorEvent}}
objectbeforeunloadThe event handler IDL attribute's type is
OnBeforeUnloadEventHandler, and the return value will therefore have
been coerced into either the value null or a DOMString.
[TreatNonObjectAsNull]
callback EventHandlerNonNull = any (Event event);
typedef EventHandlerNonNull? EventHandler;
In JavaScript, any {{Function}} object implements this interface.
[object Window]" when the document is
loaded, and an alert saying "[object HTMLBodyElement]" whenever the
user clicks something in the page.
The return value of the function affects whether the event is canceled or not:
as described above, if the return value is false, the event is canceled (except for
mouseover events, where the return value has to be true to cancel the event). With
beforeunload events, the value is instead used to determine whether or not to prompt
about unloading the document.
[TreatNonObjectAsNull]
callback OnErrorEventHandlerNonNull = any ((Event or DOMString) event, optional DOMString source, optional unsigned long lineno, optional unsigned long column, optional any error);
typedef OnErrorEventHandlerNonNull? OnErrorEventHandler;
Similarly, the {{OnBeforeUnloadEventHandler/onbeforeunload}} handler has a different return value:
[TreatNonObjectAsNull]
callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event);
typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler;
event,
source, lineno, colno, and error.
event.Document objects, and Window objects| Event handler | Event handler event type |
|---|---|
onabort | abort
|
onauxclick | auxclick
|
oncancel | cancel
|
oncanplay | canplay
|
oncanplaythrough | canplaythrough
|
onchange | change
|
onclick | click
|
onclose | close
|
oncuechange | cuechange
|
ondblclick | dblclick
|
ondrag | drag
|
ondragend | dragend
|
ondragenter | dragenter
|
ondragexit | dragexit
|
ondragleave | dragleave
|
ondragover | dragover
|
ondragstart | dragstart
|
ondrop | drop
|
ondurationchange | durationchange
|
onemptied | emptied
|
onended | ended
|
oninput | input
|
oninvalid | invalid
|
onkeydown | keydown
|
onkeypress | keypress
|
onkeyup | keyup
|
onloadeddata | loadeddata
|
onloadedmetadata | loadedmetadata
|
onloadend | loadend
|
onloadstart | loadstart
|
onmousedown | mousedown
|
onmouseenter | mouseenter
|
onmouseleave | mouseleave
|
onmousemove | mousemove
|
onmouseout | mouseout
|
onmouseover | mouseover
|
onmouseup | mouseup
|
onwheel | wheel
|
onpause | pause
|
onplay | play
|
onplaying | playing
|
onprogress | progress
|
onratechange | ratechange
|
onreset | reset
|
onseeked | seeked
|
onseeking | seeking
|
onselect | select
|
onstalled | stalled
|
onsubmit | submit
|
onsuspend | suspend
|
ontimeupdate | timeupdate
|
ontoggle | toggle
|
onvolumechange | volumechange
|
onwaiting | waiting
|
| Event handler | Event handler event type |
|---|---|
onblur | blur
|
onerror | error
|
onfocus | focus
|
onload | load
|
onresize | resize
|
onscroll | scroll
|
| Event handler | Event handler event type |
|---|---|
onafterprint | afterprint
|
onbeforeprint | beforeprint
|
onbeforeunload | beforeunload
|
onhashchange | hashchange
|
onlanguagechange | languagechange
|
onmessage | message
|
onoffline | offline
|
ononline | online
|
onpagehide | pagehide
|
onpageshow | pageshow
|
onrejectionhandled | rejectionhandled
|
onpopstate | popstate
|
onstorage | storage
|
onunhandledrejection | unhandledrejection
|
onunload | unload
|
| Event handler | Event handler event type |
|---|---|
oncut | cut
|
oncopy | copy
|
onpaste | paste
|
| Event handler | Event handler event type |
|---|---|
onreadystatechange | {{global/readystatechange}} |
[NoInterfaceObject]
interface GlobalEventHandlers {
attribute EventHandler onabort;
attribute EventHandler onblur;
attribute EventHandler oncancel;
attribute EventHandler oncanplay;
attribute EventHandler oncanplaythrough;
attribute EventHandler onchange;
attribute EventHandler onclick;
attribute EventHandler onclose;
attribute EventHandler oncuechange;
attribute EventHandler ondblclick;
attribute EventHandler ondrag;
attribute EventHandler ondragend;
attribute EventHandler ondragenter;
attribute EventHandler ondragexit;
attribute EventHandler ondragleave;
attribute EventHandler ondragover;
attribute EventHandler ondragstart;
attribute EventHandler ondrop;
attribute EventHandler ondurationchange;
attribute EventHandler onemptied;
attribute EventHandler onended;
attribute OnErrorEventHandler onerror;
attribute EventHandler onfocus;
attribute EventHandler oninput;
attribute EventHandler oninvalid;
attribute EventHandler onkeydown;
attribute EventHandler onkeypress;
attribute EventHandler onkeyup;
attribute EventHandler onload;
attribute EventHandler onloadeddata;
attribute EventHandler onloadedmetadata;
attribute EventHandler onloadstart;
attribute EventHandler onmousedown;
[LenientThis] attribute EventHandler onmouseenter;
[LenientThis] attribute EventHandler onmouseleave;
attribute EventHandler onmousemove;
attribute EventHandler onmouseout;
attribute EventHandler onmouseover;
attribute EventHandler onmouseup;
attribute EventHandler onwheel;
attribute EventHandler onpause;
attribute EventHandler onplay;
attribute EventHandler onplaying;
attribute EventHandler onprogress;
attribute EventHandler onratechange;
attribute EventHandler onreset;
attribute EventHandler onresize;
attribute EventHandler onscroll;
attribute EventHandler onseeked;
attribute EventHandler onseeking;
attribute EventHandler onselect;
attribute EventHandler onstalled;
attribute EventHandler onsubmit;
attribute EventHandler onsuspend;
attribute EventHandler ontimeupdate;
attribute EventHandler ontoggle;
attribute EventHandler onvolumechange;
attribute EventHandler onwaiting;
};
[NoInterfaceObject]
interface WindowEventHandlers {
attribute EventHandler onafterprint;
attribute EventHandler onbeforeprint;
attribute OnBeforeUnloadEventHandler onbeforeunload;
attribute EventHandler onhashchange;
attribute EventHandler onlanguagechange;
attribute EventHandler onmessage;
attribute EventHandler onoffline;
attribute EventHandler ononline;
attribute EventHandler onpagehide;
attribute EventHandler onpageshow;
attribute EventHandler onrejectionhandled;
attribute EventHandler onpopstate;
attribute EventHandler onstorage;
attribute EventHandler onunhandledrejection;
attribute EventHandler onunload;
};
[NoInterfaceObject]
interface DocumentAndElementEventHandlers {
attribute EventHandler oncopy;
attribute EventHandler oncut;
attribute EventHandler onpaste;
};
click event on the element. [[!UIEVENTS]]
Firing a simple event named
e means that a trusted event with the name e, which does not
bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and
which uses the {{Event}} interface, must be created and dispatched at the given target.
Firing a synthetic mouse event named e
means that an event with the name e, which is trusted (except where otherwise
stated), does not bubble (except where otherwise stated), is not cancelable (except where
otherwise stated), and which uses the {{MouseEvent}} interface, must be created and dispatched at
the given target. The event object must have its {{MouseEvent/screenX}}, {{MouseEvent/screenY}},
{{MouseEvent/clientX}}, {{MouseEvent/clientY}}, and {{MouseEvent/button}} attributes initialized to
0, its {{MouseEvent/ctrlKey}}, {{MouseEvent/shiftKey}}, {{MouseEvent/altKey}}, and
{{MouseEvent/metaKey}} attributes initialized according to the current state of the key input
device, if any (false for any keys that are not available), its {{UIEvent/detail}} attribute
initialized to 1, its {{MouseEvent/relatedTarget}} attribute initialized to null (except where
otherwise stated), and its {{UIEvent/view}} attribute initialized to the {{Window}} object of
the {{Document}} object of the given target node, if any, or else null. The
{{MouseEvent/getModifierState()}} method on the object must return values appropriately describing
the state of the key input device at the time the event is created.
Firing a click event means
firing a synthetic mouse event named click, which bubbles and is cancelable.
The default action of these events is to do nothing except where otherwise stated.
Window objectDocument in a browsing
context, if the event is not a load event, the user agent
must act as if, for the purposes of event dispatching,
the Window object is the parent of the Document object. [[!DOM]]
Other specifications are encouraged to further extend it using partial interface
{{WindowOrWorkerGlobalScope}} { … }; along with an appropriate reference.
typedef (DOMString or Function) TimerHandler;
[NoInterfaceObject, Exposed=(Window, Worker)]
interface WindowOrWorkerGlobalScope {
[Replaceable] readonly attribute USVString origin;
// Base64 utility methods (WindowBase64)
DOMString btoa(DOMString btoa);
DOMString atob(DOMString atob);
// Timers (WindowTimers)
long setTimeout((Function or DOMString) handler, optional long timeout = 0, any... arguments);
void clearTimeout(optional long handle = 0);
long setInterval((Function or DOMString) handler, optional long timeout = 0, any... arguments);
void clearInterval(optional long handle = 0);
// ImageBitmap, Images (ImageBitmapFactories)
Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image);
Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh);
};
Window implements WindowOrWorkerGlobalScope;
WorkerGlobalScope implements WindowOrWorkerGlobalScope;
self.origin over
location.origin. self.origin returns the origin of the
environment, while location.origin returns URL of the environment.
Imagine the following script executing in a document on https://example.com:
var frame = document.createElement("iframe")
frame.onload = function() {
var frameWin = frame.contentWindow
console.log(frameWin.location.origin) // "null"
console.log(frameWin.origin) // "https://example.com"
}
document.body.appendChild(frame)
self.origin is a more reliable security indicator.
origin attribute's getter must return this object's relevant
setting object's origin, serialized.
atob() and btoa() methods allow authors to transform content to and from
the base64 encoding.
In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.
btoa( data )atob( data )btoa() method must throw an
{{InvalidCharacterError}} exception if the method's first argument contains any character
whose code point is greater than U+00FF. Otherwise, the user agent must convert that argument to a
sequence of octets whose nth octet is the eight-bit representation of the code
point of the nth character of the argument, and then must apply the base64
algorithm to that sequence of octets, and return the result. [[!RFC4648]]
The atob() method must run the following
steps to parse the string passed in the method's first argument:
| Character | Number |
|---|---|
| A | 0 |
| B | 1 |
| C | 2 |
| D | 3 |
| E | 4 |
| F | 5 |
| G | 6 |
| H | 7 |
| I | 8 |
| J | 9 |
| K | 10 |
| L | 11 |
| M | 12 |
| N | 13 |
| O | 14 |
| P | 15 |
| Q | 16 |
| R | 17 |
| S | 18 |
| T | 19 |
| U | 20 |
| V | 21 |
| W | 22 |
| X | 23 |
| Y | 24 |
| Z | 25 |
| a | 26 |
| b | 27 |
| c | 28 |
| d | 29 |
| e | 30 |
| f | 31 |
| g | 32 |
| h | 33 |
| i | 34 |
| j | 35 |
| k | 36 |
| l | 37 |
| m | 38 |
| n | 39 |
| o | 40 |
| p | 41 |
| q | 42 |
| r | 43 |
| s | 44 |
| t | 45 |
| u | 46 |
| v | 47 |
| w | 48 |
| x | 49 |
| y | 50 |
| z | 51 |
| 0 | 52 |
| 1 | 53 |
| 2 | 54 |
| 3 | 55 |
| 4 | 56 |
| 5 | 57 |
| 6 | 58 |
| 7 | 59 |
| 8 | 60 |
| 9 | 61 |
| + | 62 |
| / | 63 |
The discarded bits mean that, for instance, atob("YQ") and
atob("YR") both return "<{a}>".
APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser) or XML documents (and the XML parser).
{{Document}} objects have a throw-on-dynamic-markup-insertion counter, which is used in conjunction with the [=create an element for the token=] algorithm to prevent [=custom element constructors=] from being able to use {{Document/open()|document.open()}}, {{Document/close()|document.close()}}, and {{Document/write()|document.write()}} when they are invoked by the parser. Initially, the counter must be set to zero.open()
method comes in several variants with different numbers of arguments.
[[#text-html|text/html]]", then the resulting {{Document}} has an HTML
parser associated with it, which can be given data to parse using
{{Document/write()|document.write()}}. Otherwise, all content passed to
{{Document/write()|document.write()}} will be parsed as plain text.
If the replace argument is present and has the value "replace", the
existing entries in the session history for the {{Document}} object are removed.
The method has no effect if the {{Document}} is still being parsed.
Throws an "{{InvalidStateError}}" {{DOMException}} if the {{Document}} is an
XML document.
replace", then let replace be true.
Otherwise, if the browsing context's session history contains only one
{{Document}}, and that was the about:blank {{Document}} created
when the browsing context was created, and
that {{Document}} has never had the unload a document algorithm invoked on it (e.g.,
by a previous call to {{Document/open()|document.open()}}), then let replace be
true.
Otherwise, let replace be false.
6. If the {{Document}} has an active parser whose script nesting level is greater
than zero, then the method does nothing. Abort these steps and return the {{Document}} object
on which the method was invoked.
This basically causes {{Document/open()|document.open()}} to be ignored when it's called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler.
7. Similarly, if the {{Document}}'s ignore-opens-during-unload counter is greater than zero, then the method does nothing. Abort these steps and return the {{Document}} object on which the method was invoked.This basically causes {{Document/open()|document.open()}} to be ignored when
it's called from a beforeunload pagehide, or unload
event handler while the {{Document}} is being unloaded.
Document to the
{{Document}}.
17. Set up a browsing context environment settings object with
realm execution context.
18. Replace the {{Document}}'s singleton objects with new instances of those objects, created in
window's Realm. (This includes in particular the
{{History}} and {{Navigator}} objects, the various {{BarProp}}
objects, the two Storage objects, the various {{HTMLCollection}} objects, and
objects defined by other specifications, like Selection. It also includes all
the Web IDL prototypes in the JavaScript binding, including the {{Document}} object's
prototype.)
19. Change the document's character encoding to UTF-8.
20. If the {{Document}} is [=ready for post-load tasks=], then set the {{Document}} object's
reload override flag and set the {{Document}}'s reload override buffer to the
empty string.
21. Set the {{Document}}'s salvageable state back to true.
22. Change the document's [=document url|URL=] to the [=document url|URL=] of the
responsible document specified by the entry settings object.
23. If the {{Document}}'s iframe load in progress flag is set, set the {{Document}}'s
mute iframe load flag.
24. Create a new HTML parser and associate it with the document. This is a
script-created parser (meaning that it can be closed by the
{{Document/open()|document.open()}} and {{Document/close()|document.close()}} methods, and
that the tokenizer will wait for an explicit call to {{Document/close()|document.close()}}
before emitting an end-of-file token). The encoding confidence is irrelevant.
25. Set the current document readiness of the document to "loading".
26. If type is an ASCII case-insensitive match for the string
"replace", then, for historical reasons, set it to the string
"[[#text-html|text/html]]".
Otherwise:
If the type string contains a U+003B SEMICOLON character (;), remove the first
such character and all characters from it up to the end of the string.
Strip leading and trailing white space from type.
27. If type is not now an ASCII case-insensitive match for the string
"[[#text-html|text/html]]", then act as if the tokenizer had emitted a
start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character,
then switch the HTML parser's tokenizer to the [[#plaintext-state]].
28. Remove all the entries in the browsing context's session history after the
current entry. If the current entry is the last entry in the session history,
then no entries are removed.
This doesn't necessarily have to affect the user agent's user interface.
29. Remove any tasks queued by the history traversal task source that are associated with any {{Document}} objects in the top-level browsing context's document family. 30. Remove any earlier entries that share the same {{Document}}. 31. If replace is false, then add a new entry, just before the last entry, and associate with the new entry the text that was parsed by the previous parser associated with the {{Document}} object, as well as the state of the document at the start of these steps. This allows the user to step backwards in the session history to see the page before it was blown away by the {{Document/open()|document.open()}} call. This new entry does not have a {{Document}} object, so a new one will be created if the session history is traversed to that entry. 32. Set the {{Document}}'s fired unload flag to false. (It could have been set to true during the unload step above.) 33. Finally, set the insertion point to point at just before the end of the input stream (which at this point will be empty). 34. Return the {{Document}} on which the method was invoked.The {{Document/open()|document.open()}} method does not affect whether a {{Document}} is [=ready for post-load tasks=] or completely loaded.
When called with four arguments, the {{Document/open()}} method on the {{Document}} object must call the {{Window/open()}} method on the {{Window}} object of the {{Document}} object, with the same arguments as the original call to the {{Document/open()}} method, and return whatever that method returned. If the {{Document}} object has no {{Window}} object, then the method must throw an "{{InvalidAccessError}}" {{DOMException}}.document.open() method.
Throws an {{InvalidStateError}} exception if the {{Document}} is an XML document.
close() method must run the following steps:
1. If the {{Document}} object is an XML document, then throw an {{InvalidStateError}}
exception and abort these steps.
2. If there is no script-created parser associated with the document, then abort these
steps.
3. Insert an explicit "EOF" character at the end of the parser's input stream.
4. If there is a pending parsing-blocking script, then abort these steps.
5. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the
tokenizer reaches the explicit "EOF" character or spins the event loop.
Document's input stream.
This method has very idiosyncratic behavior. In some cases, this method can affect the state
of the HTML parser while the parser is running, resulting in a DOM that does not
correspond to the source of the document (e.g., if the string written is the string
"<plaintext>" or "<!--"). In other cases, the call can
clear the current page first, as if document.open() had been called. In yet
more cases, the method is simply ignored, or throws an exception. To make matters worse, the
exact behavior of this method can in some cases be dependent on network latency, which can
lead to failures that are very hard to debug. For all these reasons, use of this
method is strongly discouraged.
Document objects have an ignore-destructive-writes counter, which is
used in conjunction with the processing of <{script}> elements to prevent external
scripts from being able to use {{Document/write()|document.write()}} to blow
away the document by implicitly calling document.open().
Initially, the counter must be set to zero.
The document.write(...) method must act as
follows:
Document object is not an active document, then abort
these steps.Document's
ignore-opens-during-unload counter is greater than zero or the
Document's ignore-destructive-writes counter is greater than zero,
abort these steps.
open() method on the document
object (with no arguments). If the user refused to allow the document to be unloaded, then abort these steps. Otherwise, the insertion point will point
at just before the end of the (empty) input stream.
Document object's reload override flag is set, then append
the string consisting of the concatenation of all the arguments to the method to the
Document's reload override buffer.
script end tag token is emitted by the tokenizer).
If the {{Document/write()|document.write()}} method was
called from script executing inline (i.e., executing because the parser parsed a set of
script tags), then this is a reentrant invocation of the
parser.
document.writeln()Document's input stream, followed by a newline
character. If necessary, calls the open() method
implicitly first.
This method throws an {{InvalidStateError}} exception when invoked on XML
documents.
document.writeln(...) method, when
invoked, must act as if the {{Document/write()|document.write()}} method had
been invoked with the same argument(s), plus an extra argument consisting of a string containing a
single line feed character (U+000A).
setTimeout()
and setInterval()
methods allow authors to schedule timer-based callbacks.
setTimeout( handler [, timeout [, arguments... ] ] )setTimeout( code [, timeout ] )clearTimeout( handle )setTimeout()
or setInterval() identified by
handle.
setInterval( handler [, timeout [, arguments... ] ] )setInterval( code [, timeout ] )clearInterval( handle )setInterval()
or setTimeout() identified by handle.
Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.
This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.
Objects that implement theWindowTimers interface have a list of active
timers. Each entry in this lists is identified by a number, which must be unique within the
list for the lifetime of the object that implements the WindowTimers interface.
setTimeout() method must return
the value returned by the timer initialization steps, passing them the method's
arguments, the object on which the method for which the algorithm is running is implemented (a
Window or WorkerGlobalScope object) as the method
context, and the repeat flag set to false.
The setInterval() method must
return the value returned by the timer initialization steps, passing them the
method's arguments, the object on which the method for which the algorithm is running is
implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to true.
The clearTimeout() and clearInterval() methods must clear the
entry identified as handle from the list of active timers of the
WindowTimers object on which the method was invoked, if any, where handle is the argument passed to the method. (If handle does
not identify an entry in the list of active timers of the WindowTimers
object on which the method was invoked, the method does nothing.)
Because clearTimeout() and
clearInterval() clear entries from the same
list, either method can be used to clear timers created by
setTimeout() or
setInterval().
WorkerGlobalScope object, or else the WindowProxy that corresponds
to method context.FunctionFunction. Use the third and subsequent method
arguments (if any) as the arguments for invoking the Function. Use method context proxy as the
Callback this value. [[!ECMA-262]]
Let fetch options be a set of script fetch options object whose cryptographic nonce is initiating script's fetch options's
cryptographic nonce, integrity metadata is the empty string,
parser metadata is "not-parser-inserted",
credentials mode is initiating script's
fetch options's credentials mode, and referrer policy
is initiating script's fetch options's referrer policy.
The effect of these options ensures that the string compilation done by
setTimeout() and setInterval() behaves equivalently to that done by
eval(). That is, module script fetches via import()
will behave the same in both contexts.
Window object, wait until the
Document associated with method context has been fully
active for a further timeout milliseconds (not necessarily
consecutively).
Otherwise, method context is a WorkerGlobalScope object;
wait until timeout milliseconds have passed with the worker not suspended
(not necessarily consecutively).
Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the
algorithms defined in Web IDL, before this algorithm is invoked.
ONE TWO ":
var log = '';
function logger(s) { log += s + ' '; }
setTimeout({ toString: function () {
setTimeout("logger('ONE')", 100);
return "logger('TWO')";
} }, 100);
This is intended to allow user agents to pad timeouts as needed to optimize the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.
Once the task has been processed, if the repeat flag is false, it is safe to remove the entry for handle from the list of active timers (there is no way for the entry's existence to be detected past this point, so it does not technically matter one way or the other).
function doExpensiveWork() {
var done = false;
// ...
// this part of the function takes up to five milliseconds
// set done to true if we're done
// ...
return done;
}
function rescheduleWork() {
var handle = setTimeout(rescheduleWork, 0); // preschedule next iteration
if (doExpensiveWork())
clearTimeout(handle); // clear the timeout if we don't need it
}
function scheduleWork() {
setTimeout(rescheduleWork, 0);
}
scheduleWork(); // queues a task to do lots of work
Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.
To optionally truncate a simple dialog string s, return either s itself or some string derived from s that is shorter. User agents should not provide UI for displaying the elided portion of s, as this makes it too easy for abusers to create dialogs of the form "Important security alert! Click 'Show More' for full details!".For example, a user agent might want to only display the first 100 characters of a message. Or, a user agent might replace the middle of the string with "…". These types of modifications can be useful in limiting the abuse potential of unnaturally large, trustworthy-looking system dialogs.
Thealert(message)
method, when invoked, must run the following steps:
confirm(message)
method, when invoked, must run the following steps:
prompt(message, default)
method, when invoked, must run the following steps:
print() method is invoked, if the
Document is [=ready for post-load tasks=], then the user agent must
run the printing steps in parallel. Otherwise, the user agent must only set the
print when loaded flag on the {{Document}}.
User agents should also run the printing steps whenever the user asks for the
opportunity to obtain a physical form (e.g., printed copy), or the representation of a
physical form (e.g., PDF copy), of a document.
The printing steps are as follows:
For instance, a kiosk browser could silently ignore any invocations of the
print() method.
For instance, a browser on a mobile device could detect that there are no printers in the vicinity and display a message saying so before continuing to offer a "save to PDF" option.
If the printing dialog is blocked by a Document's sandbox,
then neither the beforeprint nor afterprint events will be fired.
beforeprint at the Window object of the
Document that is being printed, as well as any nested browsing contexts in it.
The beforeprint event can be used to
annotate the printed copy, for instance adding the time at which the document was printed.
afterprint at the Window object of the
Document that is being printed, as well as any nested browsing contexts in it.
The afterprint event can be used to
revert annotations added in the earlier event, as well as showing post-printing UI. For
instance, if a page is walking the user through the steps of applying for a home loan, the
script could automatically advance to the next step after having printed a form or other.
Navigator objectnavigator attribute of the
{{Window}} interface must return an instance of the Navigator interface,
which represents the identity and state of the user agent (the client), and allows Web pages to
register themselves as potential protocol handlers:
interface Navigator {
// objects implementing this interface also implement the interfaces given below
};
Navigator implements NavigatorID;
Navigator implements NavigatorLanguage;
Navigator implements NavigatorOnLine;
Navigator implements NavigatorContentUtils;
Navigator implements NavigatorCookies;
These interfaces are defined separately so that other specifications can re-use parts of the
Navigator interface.
[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorID {
[Exposed=Window] readonly attribute DOMString appCodeName; // constant "Mozilla"
readonly attribute DOMString appName; // constant "Netscape"
readonly attribute DOMString appVersion;
readonly attribute DOMString platform;
[Exposed=Window]readonly attribute DOMString product; // constant "Gecko"
readonly attribute DOMString userAgent;
};
In certain cases, despite the best efforts of the entire industry, Web browsers have bugs and
limitations that Web authors are forced to work around.
This section defines a collection of attributes that can be used to determine, from script, the
kind of user agent in use, in order to work around these issues.
Client detection should always be limited to detecting known current versions; future versions
and unknown versions should always be assumed to be fully compliant.
navigator . appCodeNameMozilla".
navigator . appNameNetscape".
navigator . appVersionnavigator . platformnavigator . productGecko".
navigator . productSub()20030107", or the string "20100101".
navigator . userAgentappCodeNameMozilla".appNameNetscape".appVersion4.0" or a string representing the
version of the browser in detail, e.g., "1.0 (VMS; en-US)
Mellblomenator/9000".platformMacIntel", "Win32",
"FreeBSD i386", "WebTV OS".productGecko".taintEnabled()userAgentUser-Agent" header
in HTTP requests, or the empty string if no such header is ever sent.Any information in this API that varies from user to user can be used to profile the user. In fact, if enough such information is available, a user can actually be uniquely identified. For this reason, user agent implementors are strongly urged to include as little information in this API as possible.
[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorLanguage {
readonly attribute DOMString? language;
readonly attribute DOMString[] languages;
};
navigator . languagenavigator . languagesnavigator.language.
A languagechange event is fired at the
Window or WorkerGlobalScope object when the user agent's understanding
of what the user's preferred languages are changes.
languagelanguagesnavigator.languages attribute of a Window
or WorkerGlobalScope object return a new set of language tags, the user agent must
queue a task to fire a simple event named languagechange at the Window or
WorkerGlobalScope object and wait until that task begins to be executed before
actually returning a new value.
The task source for this task is the
DOM manipulation task source.
en-US" is
suggested; if all users of the service use that same value, that reduces the possibility of
distinguishing the users from each other.Accept-Language header.
registerProtocolHandler() method
[NoInterfaceObject]
interface NavigatorContentUtils {
void registerProtocolHandler(DOMString scheme, DOMString url, DOMString title);
void unregisterProtocolHandler(DOMString scheme, DOMString url);
};
The registerProtocolHandler(DOMString scheme, DOMString url, DOMString title) method
allows Web sites to register themselves as possible handlers for particular schemes. For example,
an online telephone messaging service could register itself as a handler of the sms:
scheme, so that if the user clicks on such a link, the user is given the opportunity to use that
Web site. [[!RFC5724]]]
navigator . registerProtocolHandler(scheme, url, title)%s" in the URL is used as a placeholder for where to put
the URL of the content to be handled.
Throws a "{{SecurityError}}" {{DOMException}} if the user agent blocks the registration (this
might happen if trying to register as a handler for "http", for instance).
Throws a "{{SyntaxError}}" {{DOMException}} if the "%s" string is
missing in the URL.
mailto" or "web+auth". The
scheme must be compared in an ASCII case-insensitive manner by user agents for the
purposes of comparing with the scheme part of URLs that they consider against the list of
registered handlers.
The scheme value, if it contains a colon (as in "mailto:"),
will never match anything, since schemes don't contain colons.
If the registerProtocolHandler()
method is invoked with a scheme that is neither a safelisted scheme nor a scheme
whose value starts with the substring "web+" and otherwise contains only
lowercase ASCII letters, and whose length is at least five characters (including
the "web+" prefix), the user agent must throw a "{{SyntaxError}}" {{DOMException}}.
The following schemes are the safelisted schemes:
bitcoingeoimircircsmagnetmailtommsnewsnntpopenpgp4fprsipsmssmstosshtelurnwebcalwtaixmppThis list can be changed. If there are schemes that should be added, please send feedback.
This list excludes any schemes that could reasonably be expected to be supported
inline, e.g., in an <{iframe}>, such as http or (more
theoretically) gopher. If those were supported, they could potentially be
used in man-in-the-middle attacks, by replacing pages that have frames with such content with
content under the control of the protocol handler. If the user agent has native support for the
schemes, this could further be used for cookie-theft attacks.
%s".
User agents must throw a "{{SyntaxError}}" {{DOMException}} if parsing the url
argument relative to the API base URL specified by the entry settings object is
not successful.
The resulting URL string would by definition not be a valid URL
as it would include the string "%s" which is not a valid
component in a URL.
This is forcibly the case if the %s placeholder is in the
scheme, host, or port parts of the URL.
%s" in the url argument with an
escaped version of the absolute URL of the content in question (as defined below),
then parse the resulting URL, relative to the API
base URL specified by the entry settings object at the time the registerProtocolHandler() method was
invoked, and then navigate an appropriate browsing
context to the resulting URL.
To get the escaped version of the absolute URL of the content in question, the
user agent must replace every character in that absolute URL that is not a
character in the URL default encode set with the result of UTF-8 percent encoding that character.
https://example.com/ that made the
following call:
navigator.registerProtocolHandler('web+soup', 'soup?url=%s', 'SoupWeb™')
...and then, much later, while visiting https://www.example.net/,
clicked on a link such as:
chickenkïwi.soup file was served with the
MIME type application/x-soup, the user agent might navigate to the
following URL:
https://example.com/soup?url=web+soup:chickenk%C3%AFwi.soupThis site could do whatever it is that it does with soup (synthesize it and ship it to the user, or whatever).
navigator . unregisterProtocolHandler(scheme, url)%s", abort these steps. There's no
matching handler.
2. Parse the string relative to the entry settings object. If this fails, then
throw a "{{SyntaxError}}" {{DOMException}}.
3. If the resulting URL record's origin is not the same origin as the
[=concept/origin=] specified by the entry settings object, throw a
"{{SecurityError}}" {{DOMException}}.
4. Return the resulting URL string as the result of preprocessing the argument.
http or https, to be
rerouted through third-party sites. This would allow a user's activities to be trivially tracked,
and would allow user information, even in secure connections, to be collected.
Hijacking defaults. User agents are strongly urged to not automatically change
any defaults, as this could lead the user to send data to remote hosts that the user is not
expecting. New handlers registering themselves should never automatically cause those sites to be
used.
Registration spamming. User agents should consider the possibility that a site
will attempt to register a large number of handlers, possibly from multiple domains (e.g., by
redirecting through a series of pages each on a different domain, and each registering a handler
for web+spam: — analogous practices abusing other Web browser features have
been used by pornography Web sites for many years). User agents should gracefully handle such
hostile attempts, protecting the user.
Misleading titles. User agents should not rely wholly on the title
argument to the methods when presenting the registered handlers to the user, since sites could
easily lie. For example, a site hostile.example.net could claim that it was
registering the "Cuddly Bear Happy Scheme Handler". User agents should therefore use the
handler's domain in any UI along with any title.
Hostile handler metadata. User agents should protect against typical attacks
against strings embedded in their interface, for example ensuring that markup or escape characters
in such strings are not executed, that null bytes are properly handled, that over-long strings do
not cause crashes or buffer overruns, and so forth.
Leaking Intranet URLs. The mechanism described in this section can result in
secret Intranet URLs being leaked, in the following manner:
https://www.corp.example.com/upcoming-aquisitions/the-sample-company.egf, which
might tell the third party that Example Corporation is intending to merge with The Sample Company.
Implementors might wish to consider allowing administrators to disable this feature for certain
subdomains or schemes.
Leaking secure URLs. User agents should not send HTTPS URLs to third-party
sites registered as scheme handlers without the user's informed consent, for the same reason that
user agents sometimes avoid sending Referer (sic) HTTP
headers from secure sites to third-party sites.
Leaking credentials. User agents must never send username or password
information in the URLs that are escaped and included sent to the handler sites. User agents may
even avoid attempting to pass to Web-based handlers the URLs of resources that are known to
require authentication to access, as such sites would be unable to access the resources in
question without prompting the user for credentials themselves (a practice that would require the
user to know whether to trust the third-party handler, a decision many users are unable to make or
even understand).
Interface interference. User agents should be prepared to handle intentionally
long arguments to the methods. For example, if the user interface exposed consists of an "accept"
button and a "deny" button, with the "accept" binding containing the name of the handler, it's
important that a long name not cause the "deny" button to be pushed off the screen.
Fingerprinting users. Since a site can detect if it has attempted to register
a particular handler or not, whether or not the user responds, the mechanism can be used to store
data. User agents are therefore strongly urged to treat registrations in the same manner as
cookies: clearing cookies for a site should also clear all registrations for that site, and
disabling cookies for a site should also disable registrations.
[NoInterfaceObject]
interface NavigatorCookies {
readonly attribute boolean cookieEnabled;
};
navigator . cookieEnabledcookieEnabled attribute must
return true if the user agent attempts to handle cookies according to the cookie specification,
and false if it ignores cookie change requests. [[!COOKIES]]
[Exposed=(Window, Worker), Serializable, Transferable]
interface ImageBitmap {
readonly attribute unsigned long width;
readonly attribute unsigned long height;
};
typedef (HTMLImageElement or
HTMLVideoElement or
HTMLCanvasElement or
Blob or
ImageData or
CanvasRenderingContext2D or
ImageBitmap) ImageBitmapSource;
An ImageBitmap object represents a bitmap image that can be painted to a canvas
without undue latency.
The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.
createImageBitmap(image [, sx, sy, sw, sh ] )Blob object, an
ImageData object, a CanvasRenderingContext2D object, or another
ImageBitmap object, and returns a promise that is resolved when a new
ImageBitmap is created.
If no ImageBitmap object can be constructed, for example because the provided
image data is not actually an image, then the promise is rejected instead.
If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with
any pixels missing in the original replaced by transparent black. These coordinates are in the
source image's pixel coordinate space, not in CSS pixels.
Rejects the promise with an {{InvalidStateError}} exception if the source image is not in a valid
state (e.g., an <{img}> element that hasn't finished loading, or a
CanvasRenderingContext2D object whose bitmap data has zero length along one or both
dimensions, or an ImageData object whose data is data attribute has been neutered). Rejects the promise with a "{{SyntaxError}}" {{DOMException}} if the script is not allowed to access the image data of the source image (e.g., a
video that is CORS-cross-origin, or a canvas being drawn
on by a script in a worker from another [=concept/origin=]).
widthheightImageBitmap object always has associated bitmap data, with a width and a height.
However, it is possible for this data to be corrupted. If an ImageBitmap object's
media data can be decoded without errors, it is said to be fully decodable.
An ImageBitmap object's bitmap has an origin-clean flag, which indicates whether the
bitmap is tainted by content from a different [=concept/origin=]. The flag is initially set to
true and may be changed to false by the steps of createImageBitmap().
ImageBitmap objects are serializable objects and transferable objects.
Their serialization steps, given value and serialized, are:
1. Set serialized.\[[BitmapData]] to a copy of value's bitmap data.
2. Set serialized.\[[OriginClean]] to true if value's origin-clean flag is set,
and false otherwise.
Their deserialization steps, given serialized and value, are:
1. Set value's bitmap data to serialized.\[[BitmapData]].
2. If serialized.\[[OriginClean]] is true, set value's origin-clean flag.
Their transfer steps, given value and dataHolder, are:
1. Set dataHolder.\[[BitmapData]] to value's bitmap data.
2. Set dataHolder.\[[OriginClean]] to true if value's origin-clean flag is set,
and false otherwise.
3. Unset value's bitmap data.
Their transfer-receiving steps, given dataHolder and value, are:
1. Set value's bitmap data to dataHolder.\[[BitmapData]].
2. If dataHolder.\[[OriginClean]] is true, set value's origin-clean flag.
ImageBitmap object can be obtained from a variety of different objects, using
the
createImageBitmap()
method. When invoked, the method must act as follows:
ImageBitmap object.ImageBitmap object's bitmap data be a copy of the img
element's media data, cropped to the source rectangle. If this is an animated
image, the ImageBitmap object's bitmap data must only be taken from the default
image of the animation (the one that the format defines is to be used when animation is not
supported or is disabled), or, if there is no such image, the first frame of the
animation.ImageBitmap object's bitmap to false.ImageBitmap object as the value.networkState attribute is NETWORK_EMPTY, then return a promise rejected with an
{{InvalidStateError}} exception and abort these steps.readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return a promise rejected with an
{{InvalidStateError}} exception and abort these steps.ImageBitmap object.ImageBitmap object's bitmap data be a copy of the frame at the
current playback position, at the media resource's intrinsic width
and intrinsic height (i.e., after any aspect-ratio
correction has been applied), cropped to the source rectangle.
ImageBitmap object's bitmap to false.ImageBitmap object as the value.ImageBitmap object.ImageBitmap object's bitmap data be a copy of the
<{canvas}> element's bitmap data, cropped to the source
rectangle.ImageBitmap object's bitmap to the
same value as the origin-clean flag of the <{canvas}> element's bitmap.ImageBitmap object as the value.Blob object
Blob object's data. If an error occurs during reading of the object,
then reject the promise with an {{InvalidStateError}} exception, and abort these steps.Blob (as given
by the Blob object's type attribute) giving the
official type.ImageBitmap object.ImageBitmap object's bitmap data be the image data read from the
Blob object, cropped to the source rectangle. If this is an animated
image, the ImageBitmap object's bitmap data must only be taken from the default
image of the animation (the one that the format defines is to be used when animation is not
supported or is disabled), or, if there is no such image, the first frame of the
animation.ImageBitmap object as the value.ImageData object
data
attribute has been neutered, return a promise rejected with an
{{InvalidStateError}} exception and abort these steps.ImageBitmap object.ImageBitmap object's bitmap data be the image data given by the
ImageData object, cropped to the source rectangle.ImageBitmap object as the value.CanvasRenderingContext2D object
CanvasRenderingContext2D object's scratch bitmap has
either a horizontal dimension or a vertical dimension equal to zero, then return a promise rejected with an
{{InvalidStateError}} exception and abort these steps.ImageBitmap object.ImageBitmap object's bitmap data be a copy of the
CanvasRenderingContext2D object's scratch bitmap, cropped to
the source rectangle.ImageBitmap object's bitmap to the same value as the origin-clean flag of the
CanvasRenderingContext2D object's scratch bitmapImageBitmap object as the value.ImageBitmap object
ImageBitmap object.ImageBitmap object's bitmap data be a copy of the image
argument's bitmap data, cropped to the source rectangle.ImageBitmap object's bitmap to the same value as the origin-clean flag of the bitmap of the
image argument.ImageBitmap object as the value.If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point. If any of the pixels on this rectangle are outside the area where the input bitmap was placed, then they will be transparent black in output.
width attribute must return the ImageBitmap object's
width, in CSS pixels.
The height attribute must return the ImageBitmap object's
height, in CSS pixels.
var sprites = {};
function loadMySprites() {
var image = new Image();
image.src = 'mysprites.png';
var resolver;
var promise = new Promise(function (arg) { resolver = arg });
image.onload = function () {
resolver(Promise.all(
createImageBitmap(image, 0, 0, 40, 40).then(function (image) { sprites.woman = image }),
createImageBitmap(image, 40, 0, 40, 40).then(function (image) { sprites.man = image }),
createImageBitmap(image, 80, 0, 40, 40).then(function (image) { sprites.tree = image }),
createImageBitmap(image, 0, 40, 40, 40).then(function (image) { sprites.hut = image }),
createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple = image }),
createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake = image }),
));
};
return promise;
}
function runDemo() {
var canvas = document.querySelector('canvas#demo');
var context = canvas.getContext('2d');
context.drawImage(sprites.tree, 30, 10);
context.drawImage(sprites.snake, 70, 10);
}
loadMySprites().then(runDemo);