Putting scripts in HTML.
This specification is an experimental breakup of the HTML specification. You can see the full list on the index page and take part in the discussion in the repository.
Various mechanisms can cause author-provided executable code to run in the context of a document. These mechanisms include, but are probably not limited to:
script
elements.javascript:
URLs.addEventListener()
, by explicit event handler content attributes, by
event handler IDL attributes, or otherwise.Scripting is enabled in a browsing context when all of the following conditions are true:
Scripting is disabled in a browsing context when any of the above conditions are false (i.e. when scripting is not enabled).
Scripting is enabled for a node if the
Document
object of the node (the node itself, if it is itself a Document
object) has an associated browsing context, and scripting is enabled in that browsing context.
Scripting is disabled for a node if there is no such browsing context, or if scripting is disabled in that browsing context.
This specification describes three kinds of JavaScript global environments: the document environment, the dedicated worker environment, and the shared worker environment. The dedicated worker environment and the shared worker environment are both types of worker environments.
Except where otherwise specified, a JavaScript global environment is a document environment.
A script has:
A code entry-point represents a block of executable code that the script exposes to other scripts and to the user agent. Typically, the code corresponding to the code entry-point is executed immediately after the script is parsed, but for event handlers, it is called each time the handler is invoked.
In JavaScript script
blocks, this corresponds to the execution
context of the global code.
A flag which, if set, 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).
An environment settings object, various settings that are shared with other scripts in the same context.
An environment settings object specifies algorithms for obtaining the following:
The characteristics of the script execution environment depend on the language, and are not defined by this specification.
In JavaScript, the script execution environment consists of the interpreter,
the stack of execution contexts, the global code and function code and the
Function
objects resulting, and so forth.
An object that provides the APIs that can be called by the code in scripts that use this settings object.
This is typically a Window
object or a
WorkerGlobalScope
object. When a global object is an empty object, it
can't do anything that interacts with the environment.
If the global object is a Window
object, then, in JavaScript, the
ThisBinding of the global execution context for this script must be the Window
object's WindowProxy
object, rather than the global object. [[!ECMA262]]
This is a willful violation of the JavaScript specification current
at the time of writing (ECMAScript edition 5, as defined in section 10.4.1.1 Initial Global
Execution Context, step 3). The JavaScript specification requires that the this
keyword in the global scope return the global object, but this is not
compatible with the security design prevalent in implementations as specified herein. [[!ECMA262]]
A browsing context that is assigned responsibility for actions taken by the scripts that use this environment settings object.
When a script creates and navigates a new
top-level browsing context, the opener
attribute
of the new browsing context's Window
object will be set to the
responsible browsing context's WindowProxy
object.
An event loop that is used when it would not be immediately clear what event loop to use.
A Document
that is assigned responsibility for actions taken by the scripts that
use this environment settings object.
For example, the address of the
responsible document is used to set the address 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.
Either a Document
(specifically, the responsible document), or a
URL, which is used by some APIs to determine what value to use for the Referer
(sic) header in calls to the fetching algorithm.
A character encoding used to encode URLs by APIs called by scripts that use this environment settings object.
An absolute URL used by APIs called by scripts that use this environment settings object to resolve relative URLs.
An instrument used in security checks.
The relevant settings object for a global object o is the environment settings object whose global object is o. (There is always a 1:1 mapping of global objects to environment settings objects.)
The relevant settings object for a script s is the settings object of s.
Whenever a new Window
object is created, it must also create an environment
settings object whose algorithms are defined as follows:
When the environment settings object is created, for each language supported by the user agent, create an appropriate execution environment as defined by the relevant specification.
When a script execution environment is needed, return the appropriate one from those created when the environment settings object was created.
Return the Window
object itself.
Return the browsing context with which the Window
object is
associated.
Return the event loop that is associated with the unit of related
similar-origin browsing contexts to which the Window
object's browsing
context belongs.
Return the Document
with which the Window
is currently
associated.
Return the Document
with which the Window
is currently
associated.
Return the current character encoding of
the Document
with which the Window
is currently associated.
Return the current base URL of the
Document
with which the Window
is currently associated.
Return the origin of the Document
with which the
Window
is currently associated.
Return the effective script origin of the Document
with which the
Window
is currently associated.
Each unit of related similar-origin browsing contexts has a stack of script settings objects, which must be initially empty. When a new environment settings object is pushed onto this stack, the specified environment settings object is to be added to the stack; when the environment settings object on this stack that was most recently pushed onto it is to be popped from the stack, it must be removed. Entries on this stack can be labeled as candidate entry settings objects.
When a user agent is to jump to a code entry-point for a script s, the user agent must run the following steps:
Let context be the settings object of s.
Prepare to run a callback with context as the environment settings object. If this returns "do not run" then abort these steps.
Make the appropriate script execution environment specified by context execute the s's code entry-point.
The steps to prepare to run a callback with an environment settings object o are as follows. They return either "run" or "do not run".
If the global object specified by o is a
Window
object whose Document
object is not fully active,
then return "do not run" and abort these steps.
If scripting is disabled for the responsible browsing context specified by o, then return "do not run" and abort these steps.
Push o onto the stack of script settings objects, and label it as a candidate entry settings object.
Return "run".
The steps to clean up after running a callback are as follows:
Pop the current incumbent settings object from the stack of script settings objects.
If the stack of script settings objects is now empty, run the global script clean-up jobs. (These cannot run scripts.)
If the stack of script settings objects 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.
When a JavaScript SourceElements production is to be evaluated, the settings object of the script corresponding to that SourceElements must be pushed onto the stack of script settings objects before the evaluation begins, and popped when the evaluation ends (regardless of whether it's an abrupt completion or not).
The entry settings object is the most-recently added environment settings object in the stack of script settings objects that is labeled as a candidate entry settings object. If the stack is empty, or has no entries labeled as such, then there is no entry settings object. It is used to obtain, amongst other things, the API base URL to resolve relative URLs used in scripts running in that unit of related similar-origin browsing contexts.
The incumbent settings object is the environment settings object in the stack of script settings objects that was most-recently added (i.e. the last one on the stack). If the stack is empty, then there is no incumbent settings object. It is used in some security checks.
The Web IDL specification also uses these algorithms. [[!WEBIDL]]
Consider the following two pages, with the first being loaded in a browser window and the
second being loaded in the iframe
of the first:
<!-- a/a.html --> <!DOCTYPE HTML> <title>Outer page</title> <iframe src="../b/b.html"></iframe> <input type=button onclick="frames[0].hello()" value="Hello">
<!-- b/b.html --> <!DOCTYPE HTML> <title>Inner page</title> <script> function hello() { location.assign('c.html'); } </script>
When the button is pressed in the inner frame, the outer page runs script in the inner page.
While the hello()
function is running, the entry settings
object is that of the outer file (a/a.html
), and the
incumbent settings object is that of the inner file (b/b.html
). The assign()
method uses
the entry settings object to resolve the URL, so we end up loading a/c.html
, but it uses the incumbent settings object to establish
the source browsing context, from which the referrer is established, so the Referer
header sent with the request for a/c.html
specifies the inner file's URL (the one ending with b/b.html
).
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 release blob:
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.
When the specification says that a script is to be created, given some script source, a script source URL, its scripting language, an environment settings object, and optionally a muted errors flag, the user agent must run the following steps:
Let script be a new script that this algorithm will subsequently initialise.
If scripting is disabled for browsing context passed to this algorithm, then abort these steps, as if the script source described a program that did nothing but return void.
Obtain the appropriate script execution environment for the given scripting language from the environment settings object provided.
Parse/compile/initialise the source of the script using the script execution environment, as appropriate for the scripting language, and thus obtain script's code entry-point.
Let script's settings object be the environment settings object provided.
If the muted errors flag was set, then set script's muted errors flag.
If all the steps above succeeded (in particular, if the script was compiled successfully), Jump to script's code entry-point.
Otherwise, report the error for script, with the problematic position (line number and column number), using the global object specified by the environment settings object as the target. If the error is still not handled after this, then the error may be reported to the user.
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 following script never terminates. A user agent could, after waiting for a few seconds, prompt the user to either terminate the script or let it continue.
<script> while (true) { /* loop */ } </script>
User agents are encouraged to allow users to disable scripting whenever the user is prompted
either by a script (e.g. using the window.alert()
API) or because
of a script's actions (e.g. because it has exceeded a time limit).
If scripting is disabled while a script is executing, the script should be terminated immediately.
User agents may allow users to specifically disable scripts just for the purposes of closing a browsing context.
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.
When the user agent is required to report an error for a particular script script with a particular position line:col, using a particular target target, it must run these steps, after which the error is either handled or not handled:
If target is in error reporting mode, then abort these steps; the error is not handled.
Let target be in error reporting mode.
Let message be a user-agent-defined string describing the error in a helpful manner.
Let error object be the object that represents the error: in the case of an
uncaught exception, that would be the object that was thrown; in the case of a JavaScript error
that would be an Error
object. If there is no corresponding
object, then the null value must be used instead.
Let location be an absolute URL that corresponds to the resource from which script was obtained.
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()
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()
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()
calls
mutating the document as it is parsed, or event handler content attributes spanning
multiple lines.
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.
Let event be a new trusted
ErrorEvent
object that does not bubble but is cancelable, and which has the event
name error
.
Initialise event's message
attribute to message.
Initialise event's filename
attribute to location.
Initialise event's lineno
attribute to line.
Initialise event's colno
attribute to col.
Initialise event's error
attribute to error object.
Dispatch event at target.
Let target no longer be in error reporting mode.
If event was canceled, then the error is handled. Otherwise, the error is not handled.
When the user agent is to report an exception E, the user agent must report the error for the relevant script, with the problematic position (line number and column number) in the resource containing the script, using the global object specified by the script's settings object as the target. If the error is still not handled after this, then the error may be reported to the user.
When an exception is thrown during the execution of one of the scripts associated with a
Document
, and the exception is not caught, the user agent must report the
exception.
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; unsigned long colno; any error; };
The message
attribute must return the
value it was initialised to. When the object is created, this attribute must be initialised to the
empty string. It represents the error message.
The filename
attribute must return the
value it was initialised to. When the object is created, this attribute must be initialised to the
empty string. It represents the absolute URL of the script in which the error
originally occurred.
The lineno
attribute must return the
value it was initialised to. When the object is created, this attribute must be initialised to
zero. It represents the line number where the error occurred in the script.
The colno
attribute must return the value
it was initialised to. When the object is created, this attribute must be initialised to zero. It
represents the column number where the error occurred in the script.
The error
attribute must return the value
it was initialised to. When the object is created, this attribute must be initialised to null.
Where appropriate, it is set to the object representing the error (e.g. the exception object in
the case of an uncaught DOM exception).
To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. There are two kinds of event loops: those for browsing contexts, and those for workers.
There must be at least one browsing context event loop per user agent, and at most one per unit of related similar-origin browsing contexts.
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.
An event loop has one or more task queues. A task queue is an ordered list of tasks, which are algorithms that are responsible for such work as:
Dispatching an Event
object at a particular
EventTarget
object is often done by a dedicated task.
Not all events are dispatched using the task queue, many are dispatched during other tasks.
The HTML parser tokenizing one or more bytes, and then processing any resulting tokens, is typically a task.
Calling a callback is often done by a dedicated task.
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.
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 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 that Document
) 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.
A user agent may have one storage mutex. This mutex is used to control access to shared state like cookies. At any one point, the storage mutex is either free, or owned by a particular event loop or instance of the fetching algorithm.
If a user agent does not implement a storage mutex, it is exempt from implementing the requirements that require it to acquire or release it.
User agent implementors have to make a choice between two evils. On the one hand, not implementing the storage mutex means that there is a risk of data corruption: a site could, for instance, try to read a cookie, increment its value, then write it back out, using the new value of the cookie as a unique identifier for the session; if the site does this twice in two different browser windows at the same time, it might end up using the same "unique" identifier for both sessions, with potentially disastrous effects. On the other hand, implementing the storage mutex has potentially serious performance implications: whenever a site uses Web Storage or cookies, all other sites that try to use Web Storage or cookies are blocked until the first site finishes.
So far, all browsers faced with this decision have opted to not implement the storage mutex.
Whenever a script calls into a plugin, and whenever a plugin calls into a script, the user agent must release the storage mutex.
An event loop must continually run through the following steps for as long as it exists:
Select the oldest task on one of the event
loop's task queues, if any, ignoring, in the case of a
browsing context event loop, tasks whose associated
Document
s are not fully active. The user agent may pick any task
queue. If there is no task to select, then jump to the microtasks step below.
Set the event loop's currently running task to the task selected in the previous step.
Run: Run the selected task.
Set the event loop's currently running task back to null.
If the storage mutex is now owned by the event loop, release it so that it is once again free.
Remove the task that was run in the run step above from its task queue.
Microtasks: Perform a microtask checkpoint.
Update the rendering: If this event loop is a browsing context event loop (as opposed to a worker event loop), then run the following substeps.
Let now be the value that would be returned by the Performance
object's now()
method. [[!HRT]]
Let docs be the list of Document
objects associated with the
event loop in question, sorted arbitrarily except that the following conditions
must be met:
Any Document
B that is nested through a
Document
A must be listed after A in the list.
If there are two documents A and B whose browsing contexts are both nested
browsing contexts and their browsing context
containers are both elements in the same Document
C, then the
order of A and B in the list must match the relative tree
order of their respective browsing context
containers in C.
In the steps below that iterate over docs, each Document
must be
processed in the order it is found in the list.
If there is a top-level browsing context B that the user agent
believes would not benefit from having its rendering updated at this time, then remove from
docs all Document
objects whose browsing context's
top-level browsing context is B.
Whether a top-level browsing context would benefit from having
its rendering updated depends on various factors, such as the update frequency. For example,
if the browser is attempting to achieve a 60 Hz refresh rate, then these steps are only
necessary every 60th of a second (about 16.7ms). If the browser finds that a top-level
browsing context is not able to sustain this rate, it might drop to a more sustainable
30Hz for that set of Document
s, rather than occasionally dropping frames. (This
specification does not mandate any particular model for when to update the rendering.)
Similarly, 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.
For each fully active Document
in docs, run the resize steps for
that Document
, passing in now as the timestamp. [[!CSSOMVIEW]]
For each fully active Document
in docs, run the scroll steps for
that Document
, passing in now as the timestamp. [[!CSSOMVIEW]]
For each fully active Document
in docs, evaluate media queries and
report changes for that Document
, passing in now as the
timestamp. [[!CSSOMVIEW]]
For each fully active Document
in docs, run CSS animations and send
events for that Document
, passing in now as the timestamp. [[!CSSANIMATIONS]]
For each fully active Document
in docs, run the fullscreen rendering
steps for that Document
, passing in now as the timestamp. [[!FULLSCREEN]]
For each fully active Document
in docs, run the animation frame
callbacks for that Document
, passing in now as the
timestamp.
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.
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 described in the
Web Workers section below.
Return to the first step of the event loop.
Each event loop has a microtask queue. A microtask is a task that is originally to be queued on the microtask queue rather than a task queue. There are two kinds of microtasks: solitary callback microtasks, and compound microtasks.
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:
Let the performing a microtask checkpoint flag be true.
Microtask queue handling: If the event loop's microtask queue is empty, jump to the done step below.
Select the oldest microtask on the event loop's microtask queue.
Set the event loop's currently running task to the task selected in the previous step.
Run: Run the selected task.
This might involve invoking scripted callbacks, which eventually calls the clean up after running a callback steps, which call this perform a microtask checkpoint algorithm again, which is why we use the performing a microtask checkpoint flag to avoid reentrancy.
Set the event loop's currently running task back to null.
If the storage mutex is now owned by the event loop, release it so that it is once again free.
Remove the microtask run in the step above from the microtask queue, and return to the microtask queue handling step.
Done: 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:
Let parent be the event loop's currently running task (the currently running compound microtask).
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.
Set the event loop's currently running task to subtask.
Run subtask.
Set the event loop's currently running task back to parent.
When an algorithm running in parallel is to await a stable state, the user agent must queue a microtask that runs the following steps, and must then stop executing (execution of the algorithm resumes when the microtask is run, as described in the following steps):
Run the algorithm's synchronous section.
Resumes execution of the algorithm in parallel, if appropriate, as described in the algorithm's steps.
Steps in synchronous sections are marked with ⌛.
When an algorithm says to spin the event loop until a condition goal is met, the user agent must run the following steps:
Let task be the event loop's currently running task.
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.
Let task source be task's task source.
Let old stack of script settings objects be a copy of the stack of script settings objects.
Empty the stack of script settings objects.
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.
Wait until the condition goal is met.
Queue a task to continue running these steps, using the task source task source. Wait until this new task runs before continuing these steps.
Replace the stack of script settings objects with the old stack of script settings objects.
Return to the caller.
Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until a condition goal is met. This means running the following steps:
If necessary, update the rendering or user interface of any Document
or
browsing context to reflect the current state.
Wait until the condition goal is met. While a user agent has a paused task, the corresponding event loop must not run further tasks, and any script in the currently running task must block. User agents should remain responsive to user input while paused, however, albeit in a reduced capacity since the event loop will not be doing anything.
When a user agent is to obtain the storage mutex as part of running a task, it must run through the following steps:
If the storage mutex is already owned by this task's event loop, then abort these steps.
Otherwise, pause until the storage mutex can be taken by the event loop.
Take ownership of the storage mutex.
The following task sources are used by a number of mostly unrelated features in this and other specifications.
This task source is used for features that react to DOM manipulations, such as things that happen in a non-blocking fashion when an element is inserted into the document.
This task source is used for features that react to user interaction, for example keyboard or mouse input.
Events sent in response to user input (e.g. click
events) must be fired using tasks queued with the user
interaction task source. [[!DOMEVENTS]]
This task source is used for features that trigger in response to network activity.
This task source is used to queue calls to history.back()
and similar APIs.
Many objects can have event handlers specified. These act as non-capture event listeners for the object on which they are specified. [[!DOM]]
An event handler has a name, which always starts with
"on
" and is followed by the name of the event for which it is intended.
An event handler can either have the value null, or be set
to a callback object, or be set to an internal raw uncompiled
handler. The EventHandler
callback function type describes how this is
exposed to scripts. Initially, event handlers 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.
An event handler IDL attribute is an IDL attribute for a specific event handler. The name of the IDL attribute is the same as the name of the event handler.
Event handler IDL attributes, on setting, must set the corresponding event handler to their new value, and on getting, must return the result of getting the current value of the event handler in question (this can throw an exception, in which case the getting propagates it to the caller, it does not catch it).
If an event handler IDL attribute exposes an event handler of an object that doesn't exist, it must always return null on getting and must do nothing on setting.
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.
An event handler content attribute is a content attribute for a specific event handler. The name of the content attribute is the same as the name of the event handler.
Event handler content attributes, when specified, must contain valid JavaScript
code which, when parsed, would match the FunctionBody
production after
automatic semicolon insertion. [[!ECMA262]]
When an event handler content attribute is set, the user agent must 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.
When an event handler H of an element
or object T implementing the EventTarget
interface is first set
to a non-null value, the user agent must append an event
listener to the list of event listeners
associated with T with type set to the event handler event
type corresponding to H, capture set to false, and
listener set to the event handler processing algorithm defined below. [[!DOM]]
The listener is emphatically not the event handler itself. Every event handler ends up registering the same listener, 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.
This example demonstrates the order in which event listeners are invoked. If the button in this example is clicked by the user, the page will show four alerts, with the text "ONE", "TWO", "THREE", and "FOUR" respectively.
<button id="test">Start Demo</button> <script> var button = document.getElementById('test'); button.addEventListener('click', function () { alert('ONE') }, false); button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here button.addEventListener('click', function () { alert('THREE') }, false); button.onclick = function () { alert('TWO'); }; button.addEventListener('click', function () { alert('FOUR') }, false); </script>
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:
Let callback be the result of getting the current value of the event handler H.
If callback is null, then abort these steps.
Process the Event
object E as follows:
ErrorEvent
object and the event handler IDL attribute's type is
OnErrorEventHandler
Invoke callback with five
arguments, the first one having the value of E's message
attribute, the second having the value of
E's filename
attribute, the third
having the value of E's lineno
attribute, the fourth having the value of E's colno
attribute, the fifth having the value of
E's error
attribute, and with the callback this value set to E's currentTarget
. Let return value be the
callback's return value. [[!WEBIDL]]
Invoke callback
with one argument, the value of which is the Event
object E,
with the callback this value set to E's currentTarget
. Let return value be the callback's return value. [[!WEBIDL]]
In this step, invoke means to invoke the Web IDL callback function.
If an exception gets thrown by the callback, end these steps and allow the exception to propagate. (It will propagate to the DOM event dispatch logic, which will then report the exception.)
Process return value as follows:
mouseover
error
and E is an ErrorEvent
objectIf return value is a Web IDL boolean true value, then cancel the event.
beforeunload
The 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.
If the return value is null, then cancel the event.
Otherwise, If the Event
object E is a
BeforeUnloadEvent
object, and the Event
object E's returnValue
attribute's value is the empty string, then set the returnValue
attribute's value to return value.
If return value is a Web IDL boolean false value, then cancel the event.
The EventHandler
callback function type represents a callback used for event
handlers. It is represented in Web IDL as follows:
[TreatNonObjectAsNull] callback EventHandlerNonNull = any (Event event); typedef EventHandlerNonNull? EventHandler;
In JavaScript, any Function
object implements
this interface.
For example, the following document fragment:
<body onload="alert(this)" onclick="alert(this)">
...leads to an alert saying "[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 the message to show the user.
For historical reasons, the onerror
handler has different
arguments:
[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 onbeforeunload
handler has a
different return value:
[TreatNonObjectAsNull] callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event); typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler;
An internal raw uncompiled handler is a tuple with the following information:
When the user agent is to get the current value of the event handler H, it must run these steps:
If H's value is an internal raw uncompiled handler, run these substeps:
If H is an element's event handler, then let element be the element, and document be the element's node document.
Otherwise, H is a Window
object's event handler: let element be null, and let document be the Document
most recently associated with that
Window
object.
If document is not in a browsing context, or if scripting is enabled for document's browsing context, then return null and abort the algorithm for getting the current value of the event handler.
Let body be the uncompiled script body in the internal raw uncompiled handler.
Let location be the location where the script body originated, as given by the internal raw uncompiled handler.
If element is not null and element has a form owner, let form owner be that form owner. Otherwise, let form owner be null.
Let script settings be the environment settings object
created for the Window
object with which document is
currently associated.
Obtain the script execution environment for JavaScript from script settings.
If body is not parsable as FunctionBody or if parsing detects an early error, then follow these substeps:
Set H's value to null.
Report the error for the appropriate script and with the appropriate position (line number and column number) given by location, using the global object specified by script settings as the target. If the error is still not handled after this, then the error may be reported to the user.
Jump to the step labeled end below.
FunctionBody is defined in ECMAScript edition 5 section 13 Function Definition. Early error is defined in ECMAScript edition 5 section 16 Errors. [[!ECMA262]]
If body begins with a Directive Prologue that contains a Use Strict Directive then let strict be true, otherwise let strict be false.
The terms "Directive Prologue" and "Use Strict Directive" are defined in ECMAScript edition 5 section 14.1 Directive Prologues and the Use Strict Directive. [[!ECMA262]]
Using the script execution environment obtained above, create a function object (as defined in ECMAScript edition 5 section 13.2 Creating Function Objects), with:
onerror
event handler of a Window
objectevent
, source
, lineno
, colno
, and
error
.event
.If H is an element's event handler, then let Scope be the result of NewObjectEnvironment(document, the global environment).
Otherwise, H is a Window
object's event handler: let Scope be the global environment.
If form owner is not null, let Scope be the result of NewObjectEnvironment(form owner, Scope).
If element is not null, let Scope be the result of NewObjectEnvironment(element, Scope).
NewObjectEnvironment() is defined in ECMAScript edition 5 section 10.2.2.3 NewObjectEnvironment (O, E). [[!ECMA262]]
Let function be this new function.
Let script be a new script.
Let script's code entry-point be function.
Let script's settings object be script settings.
Set H to function.
End: Return H's value.
Document
objects, and Window
objectsThe following are the event handlers (and their corresponding event handler event types) that must be
supported by all HTML elements, as both event handler content attributes
and event handler IDL attributes; and that must be
supported by all Document
and Window
objects, as event handler IDL
attributes:
Event handler | Event handler event type |
---|---|
onabort | abort
|
onautocomplete | autocomplete
|
onautocompleteerror | autocompleteerror
|
oncancel | cancel
|
oncanplay | canplay
|
oncanplaythrough | canplaythrough
|
onchange | change
|
onclick | click
|
onclose | close
|
oncontextmenu | contextmenu
|
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
|
onloadstart | loadstart
|
onmousedown | mousedown
|
onmouseenter | mouseenter
|
onmouseleave | mouseleave
|
onmousemove | mousemove
|
onmouseout | mouseout
|
onmouseover | mouseover
|
onmouseup | mouseup
|
onmousewheel | mousewheel
|
onpause | pause
|
onplay | play
|
onplaying | playing
|
onprogress | progress
|
onratechange | ratechange
|
onreset | reset
|
onseeked | seeked
|
onseeking | seeking
|
onselect | select
|
onshow | show
|
onsort | sort
|
onstalled | stalled
|
onsubmit | submit
|
onsuspend | suspend
|
ontimeupdate | timeupdate
|
ontoggle | toggle
|
onvolumechange | volumechange
|
onwaiting | waiting
|
The following are the event handlers (and their corresponding event handler event types) that must be
supported by all HTML elements other than body
and frameset
elements, as both event handler content attributes and event handler IDL
attributes; that must be supported by all Document
objects, as event handler IDL attributes; and that must be
supported by all Window
objects, as event handler IDL attributes on the
Window
objects themselves, and with corresponding event handler content
attributes and event handler IDL attributes exposed on all body
and frameset
elements that are owned by that
Window
object's Document
s:
Event handler | Event handler event type |
---|---|
onblur | blur
|
onerror | error
|
onfocus | focus
|
onload | load
|
onresize | resize
|
onscroll | scroll
|
The following are the event handlers (and their corresponding event handler event types) that must be
supported by Window
objects, as event handler IDL attributes on the
Window
objects themselves, and with corresponding event handler content
attributes and event handler IDL attributes exposed on all body
and frameset
elements that are owned by that
Window
object's Document
s:
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
|
onpopstate | popstate
|
onstorage | storage
|
onunload | unload
|
The following are the event handlers (and their corresponding event handler event types) that must be
supported on Document
objects as event handler IDL attributes:
Event handler | Event handler event type |
---|---|
onreadystatechange | readystatechange
|
[NoInterfaceObject] interface GlobalEventHandlers { attribute EventHandler onabort; attribute EventHandler onautocomplete; attribute EventHandler onautocompleteerror; attribute EventHandler onblur; attribute EventHandler oncancel; attribute EventHandler oncanplay; attribute EventHandler oncanplaythrough; attribute EventHandler onchange; attribute EventHandler onclick; attribute EventHandler onclose; attribute EventHandler oncontextmenu; 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 onmousewheel; 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 onshow; attribute EventHandler onsort; 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 onpopstate; attribute EventHandler onstorage; attribute EventHandler onunload; };
Certain operations and methods are defined as firing events on elements. For example, the click()
method on the HTMLElement
interface is defined as
firing a click
event on the element. [[!DOMEVENTS]]
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 screenX
, screenY
, clientX
, clientY
, and button
attributes initialised to 0, its ctrlKey
, shiftKey
,
altKey
, and metaKey
attributes initialised according
to the current state of the key input device, if any (false for any keys that are not available),
its detail
attribute initialised to 1, its relatedTarget
attribute initialised to null (except
where otherwise stated), and its view
attribute initialised to the Window
object of the Document
object of the given target node, if any, or else null. The 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
objectWhen an event is dispatched at a DOM node in a Document
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]]
The nodes representing HTML elements in the DOM must implement, and expose to scripts, the interfaces listed for them in the relevant sections of this specification. This includes HTML elements in XML documents, even when those documents are in another context (e.g. inside an XSLT transform).
Elements in the DOM represent things; that is, they have intrinsic meaning, also known as semantics.
For example, an ol
element represents an ordered list.
The basic interface, from which all the HTML elements' interfaces inherit, and which must be used by elements that have no additional requirements, is
the HTMLElement
interface.
interface HTMLElement : Element {
// metadata attributes
attribute DOMString title;
attribute DOMString lang;
attribute boolean translate;
attribute DOMString dir;
[SameObject] readonly attribute DOMStringMap dataset;
// microdata
attribute boolean itemScope;
[PutForwards=value] readonly attribute DOMSettableTokenList itemType;
attribute DOMString itemId;
[PutForwards=value] readonly attribute DOMSettableTokenList itemRef;
[PutForwards=value] readonly attribute DOMSettableTokenList itemProp;
readonly attribute HTMLPropertiesCollection properties;
attribute any itemValue; // acts as DOMString on setting
// user interaction
attribute boolean hidden;
void click();
attribute long tabIndex;
void focus();
void blur();
attribute DOMString accessKey;
readonly attribute DOMString accessKeyLabel;
attribute boolean draggable;
[PutForwards=value] readonly attribute DOMSettableTokenList dropzone;
attribute HTMLMenuElement? contextMenu;
attribute boolean spellcheck;
void forceSpellCheck();
// command API
readonly attribute DOMString? commandType;
readonly attribute DOMString? commandLabel;
readonly attribute DOMString? commandIcon;
readonly attribute boolean? commandHidden;
readonly attribute boolean? commandDisabled;
readonly attribute boolean? commandChecked;
};
HTMLElement implements GlobalEventHandlers;
HTMLElement implements ElementContentEditable;
interface HTMLUnknownElement : HTMLElement { };
The HTMLElement
interface holds methods and attributes related to a number of
disparate features, and the members of this interface are therefore described in various different
sections of this specification.
The HTMLUnknownElement
interface must be used for HTML elements that
are not defined by this specification (or other applicable specifications).
script
elementsrc
attribute, depends on the value of the type
attribute, but must match
script content restrictions.src
attribute, the element must be either empty or contain only
script documentation that also matches script
content restrictions.src
— Address of the resourcetype
— Type of embedded resourcecharset
— Character encoding of the external script resourceasync
— Execute script when available, without blockingdefer
— Defer script executioncrossorigin
— How the element handles crossorigin requestsinterface HTMLScriptElement : HTMLElement { attribute DOMString src; attribute DOMString type; attribute DOMString charset; attribute boolean async; attribute boolean defer; attribute DOMString? crossOrigin; attribute DOMString text; // also has obsolete members };
The script
element allows authors to include dynamic script and data blocks in
their documents. The element does not represent content for the
user.
When used to include dynamic scripts, the scripts may either be embedded inline or may be
imported from an external file using the src
attribute. If
the language is not that described by "text/javascript
", then the type
attribute must be present, as described below. Whatever
language is used, the contents of the script
element must conform with the
requirements of that language's specification.
When used to include data blocks (as opposed to scripts), the data must be embedded inline, the
format of the data must be given using the type
attribute,
the src
attribute must not be specified, and the contents of
the script
element must conform to the requirements defined for the format used.
The type
attribute gives the language of the
script or format of the data. If the attribute is present, its value must be a valid MIME
type. The charset
parameter must not be specified. The default, which
is used if the attribute is absent, is "text/javascript
".
The src
attribute, if specified, gives the
address of the external script resource to use. The value of the attribute must be a valid
non-empty URL potentially surrounded by spaces identifying a script resource of the type
given by the type
attribute, if the attribute is present, or
of the type "text/javascript
", if the attribute is absent. A resource is a
script resource of a given type if that type identifies a scripting language and the resource
conforms with the requirements of that language's specification.
The charset
attribute gives the character
encoding of the external script resource. The attribute must not be specified if the src
attribute is not present. If the attribute is set, its value
must be an ASCII case-insensitive match for one of the labels of an encoding, and must specify the same encoding as
the charset
parameter of the Content-Type
metadata of the external file, if any. [[!ENCODING]]
The async
and defer
attributes are boolean attributes that indicate how the script should be executed. The defer
and async
attributes
must not be specified if the src
attribute is not
present.
There are three possible modes that can be selected using these attributes. If the async
attribute is present, then the script will be executed
as soon as it is available, but without blocking further parsing of the page. If the async
attribute is not present but the defer
attribute is
present, then the script is executed when the page has finished parsing. If neither attribute is
present, then the script is fetched and executed immediately, before the user agent continues
parsing the page.
The exact processing details for these attributes are, for mostly historical
reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation
requirements are therefore by necessity scattered throughout the specification. The algorithms
below (in this section) describe the core of this processing, but these algorithms reference and
are referenced by the parsing rules for script
start and end tags in HTML, in foreign content,
and in XML, the rules for the document.write()
method, the handling of scripting, etc.
The defer
attribute may be specified even if the async
attribute is specified, to cause legacy Web browsers that
only support defer
(and not async
) to fall back to the defer
behaviour instead of the blocking behaviour that
is the default.
The crossorigin
attribute is a
CORS settings attribute. It controls, for scripts that are obtained from other origins, whether error information will be exposed.
Changing the src
, type
, charset
, async
, defer
, and crossorigin
attributes dynamically has no direct effect;
these attribute are only used at specific times described below.
A script
element has several associated pieces of state.
The first is a flag indicating whether or not the script block has been "already
started". Initially, script
elements must have this flag unset (script blocks,
when created, are not "already started"). The cloning
steps for script
elements must set the "already started" flag on the copy if
it is set on the element being cloned.
The second is a flag indicating whether the element was "parser-inserted".
Initially, script
elements must have this flag unset. It is set by the HTML
parser and the XML parser on script
elements they insert and
affects the processing of those elements.
The third is a flag indicating whether the element will "non-blocking". Initially,
script
elements must have this flag set. It is unset by the HTML parser
and the XML parser on script
elements they insert. In addition, whenever
a script
element whose "non-blocking" flag is set has a async
content attribute added, the element's
"non-blocking" flag must be unset.
The fourth is a flag indicating whether or not the script block is "ready to be
parser-executed". Initially, script
elements must have this flag unset (script
blocks, when created, are not "ready to be parser-executed"). This flag is used only for elements
that are also "parser-inserted", to let the parser know when to execute the
script.
The last few pieces of state are the script block's
type, the script block's character
encoding, and the script block's
fallback character encoding. They are determined when the script is prepared, based on
the attributes on the element at that time, and the
script
element's node document.
When a script
element that is not marked as being "parser-inserted"
experiences one of the events listed in the following list, the user agent must immediately
prepare the script
element:
script
element gets inserted
into a document, at the time the node is inserted
according to the DOM, after any other script
elements inserted at the same time that
are earlier in the Document
in tree order.script
element is in a Document
and a node or
document fragment is inserted into the
script
element, after any script
elements inserted at that time.script
element is in a Document
and has a src
attribute set where previously the element had no such
attribute.To prepare a script, the user agent must act as follows:
If the script
element is marked as having "already started", then
the user agent must abort these steps at this point. The script is not executed.
If the element has its "parser-inserted" flag set, then set was-parser-inserted to true and unset the element's "parser-inserted" flag. Otherwise, set was-parser-inserted to false.
This is done so that if parser-inserted script
elements fail to run
when the parser tries to run them, e.g. because they are empty or specify an unsupported
scripting language, another script can later mutate them and cause them to run again.
If was-parser-inserted is true and the element does not have an async
attribute, then set the element's
"non-blocking" flag to true.
This is done so that if a parser-inserted script
element fails to
run when the parser tries to run it, but it is later executed after a script dynamically updates
it, it will execute in a non-blocking fashion even if the async
attribute isn't set.
If the element has no src
attribute, and its child
nodes, if any, consist only of comment nodes and empty Text
nodes, then the user
agent must abort these steps at this point. The script is not executed.
If the element is not in a Document
, then the user agent must abort
these steps at this point. The script is not executed.
If either:
script
element has a type
attribute
and its value is the empty string, orscript
element has no type
attribute
but it has a language
attribute and that
attribute's value is the empty string, orscript
element has neither a type
attribute nor a language
attribute, then...let the script block's type for this
script
element be "text/javascript
".
Otherwise, if the script
element has a type
attribute, let the
script block's type for this script
element be the value of that attribute
with any leading or trailing sequences of space characters
removed.
Otherwise, the element has a non-empty language
attribute; let the script block's type for this
script
element be the concatenation of the string "text/
"
followed by the value of the language
attribute.
The language
attribute is never
conforming, and is always ignored if there is a type
attribute present.
If the user agent does not support the scripting language given by the script block's type for this script
element,
then the user agent must abort these steps at this point. The script is not executed.
If was-parser-inserted is true, then flag the element as "parser-inserted" again, and set the element's "non-blocking" flag to false.
The user agent must set the element's "already started" flag.
The state of the element at this moment is later used to determine the script source.
If the element is flagged as "parser-inserted", but the element's
node document is not the Document
of the parser that created the element,
then abort these steps.
If scripting is disabled for the script
element, then the user agent must abort these steps at this point. The script is not
executed.
The definition of scripting is disabled
means that, amongst others, the following scripts will not execute: scripts in
XMLHttpRequest
's responseXML
documents, scripts in DOMParser
-created documents, scripts in documents created by
XSLTProcessor
's transformToDocument
feature, and scripts
that are first inserted by a script into a Document
that was created using the
createDocument()
API. [[!XHR]]
[[!DOMPARSING]] [[!DOM]]
If the script
element has an event
attribute and a for
attribute, then run these substeps:
Let for be the value of the for
attribute.
Let event be the value of the event
attribute.
Strip leading and trailing whitespace from event and for.
If for is not an ASCII case-insensitive match for the
string "window
", then the user agent must abort these steps at this
point. The script is not executed.
If event is not an ASCII case-insensitive match for
either the string "onload
" or the string "onload()
", then the user agent must abort these steps at this point. The script
is not executed.
If the script
element has a charset
attribute, then let the script block's character
encoding for this script
element be the result of getting an
encoding from the value of the charset
attribute.
Otherwise, let the script block's fallback
character encoding for this script
element be the same as the encoding of the document itself.
Only one of these two pieces of state is set.
If the element has a src
content attribute, run these
substeps:
Let src be the value of the element's src
attribute.
If src is the empty string, queue a task to fire
a simple event named error
at the element, and abort
these steps.
Resolve src relative to the element.
If the previous step failed, queue a task to fire a simple
event named error
at the element, and abort these
steps.
Do a potentially CORS-enabled fetch of the resulting
absolute URL, with the mode being the current state of the element's crossorigin
content attribute, the origin being
the origin of the script
element's node document, and the
default origin behaviour set to taint.
The resource obtained in this fashion can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.
For performance reasons, user agents may start fetching the script (as defined above) as
soon as the src
attribute is set, instead, in the hope
that the element will be inserted into the document (and that the crossorigin
attribute won't change value in the
meantime). Either way, once the element is inserted into the document, the load must have started as described in this
step. If the UA performs such prefetching, but the element is never inserted in the document,
or the src
attribute is dynamically changed, or the crossorigin
attribute is dynamically changed, then the
user agent will not execute the script so obtained, and the fetching process will have been
effectively wasted.
Then, the first of the following options that describes the situation must be followed:
src
attribute, and the element has a defer
attribute, and
the element has been flagged as "parser-inserted", and the element does not have
an async
attributeThe element must be added to the end of the list of scripts that will execute when the
document has finished parsing associated with the Document
of the parser
that created the element.
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
src
attribute, and the element has been flagged as
"parser-inserted", and the element does not have an async
attributeThe element is the pending parsing-blocking script of the
Document
of the parser that created the element. (There can only be one such
script per Document
at a time.)
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
src
attribute, and the element has been flagged as
"parser-inserted", and either the parser that created the script
is
an XML parser or it's an HTML parser whose script nesting
level is not greater than one, and the Document
of the HTML
parser or XML parser that created the script
element has
a style sheet that is blocking scriptsThe element is the pending parsing-blocking script of the
Document
of the parser that created the element. (There can only be one such
script per Document
at a time.)
Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
src
attribute, does not have an async
attribute, and does not have the
"non-blocking" flag setThe element must be added to the end of the list of scripts that will execute in order
as soon as possible associated with the node document of the script
element at the time the prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:
If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.
Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.
Remove the first element from this list of scripts that will execute in order as soon as possible.
If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.
src
attributeThe element must be added to the set of scripts that will execute as soon as
possible of the node document of the script
element at the time the
prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.
Fetching an external script must delay the load event of the element's node document until the task that is queued by the networking task source once the resource has been fetched (defined above) has been run.
The pending parsing-blocking script of a Document
is used by the
Document
's parser(s).
If a script
element that blocks a parser gets moved to another
Document
before it would normally have stopped blocking that parser, it nonetheless
continues blocking that parser until the condition that causes it to be blocking the parser no
longer applies (e.g. if the script is a pending parsing-blocking script because there
was a style sheet that is blocking scripts when it was parsed, but then the script is
moved to another Document
before the style sheet loads, the script still blocks the
parser until the style sheets are all loaded, at which time the script executes and the parser is
unblocked).
When the user agent is required to execute a script block, it must run the following steps:
If the element is flagged as "parser-inserted", but the element's
node document is not the Document
of the parser that created the element,
then abort these steps.
Jump to the appropriate set of steps from the list below:
Executing the script block must just consist of firing
a simple event named error
at the element.
Executing the script block must consist of running the following steps. For the purposes of
these steps, the script is considered to be from an external file if, while the
prepare a script algorithm above was running for this script, the
script
element had a src
attribute
specified.
Initialise the script block's source as follows:
The contents of that file, interpreted as a Unicode string, are the script source.
To obtain the Unicode string, the user agent run the following steps:
If the resource's Content Type metadata, if any, specifies a character encoding, and the user agent supports that encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.
If the algorithm above set the script block's character encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.
Let character encoding be the script block's fallback character encoding.
If the specification for the script block's type gives specific rules for decoding files in that format to Unicode, follow them, using character encoding as the character encoding specified by higher-level protocols, if necessary.
Otherwise, decode the file to Unicode, using character encoding as the fallback encoding.
The decode algorithm overrides character encoding if the file contains a BOM.
The external file is the script source. When it is later executed, it must be interpreted in a manner consistent with the specification defining the language given by the script block's type.
The value of the text
IDL attribute at the time
the element's "already started" flag was last set is the script source.
The child nodes of the script
element at the time the element's
"already started" flag was last set are the script source.
Fire a simple event named beforescriptexecute
that bubbles and is cancelable
at the script
element.
If the event is canceled, then abort these steps.
If the script is from an external file, then increment the
ignore-destructive-writes counter of the script
element's
node document. Let neutralised doc be that
Document
.
Let old script element be the value to which the script
element's node document's currentScript
object was most recently
initialised.
Initialise the script
element's node document's currentScript
object to the script
element.
Create a script, using the script
block's source, the URL from which the script was obtained, the script block's type as the scripting language, and
the environment settings object of the script
element's
node document's Window
object.
If the script came from a resource that was fetched in the steps above, and the resource was CORS-cross-origin, then pass the muted errors flag to the create a script algorithm as well.
This is where the script is compiled and actually executed.
Initialise the script
element's node document's currentScript
object to old script
element.
Decrement the ignore-destructive-writes counter of neutralised doc, if it was incremented in the earlier step.
Fire a simple event named afterscriptexecute
that bubbles (but is not
cancelable) at the script
element.
If the script is from an external file, fire a simple event named load
at the script
element.
Otherwise, the script is internal; queue a task to fire a simple
event named load
at the script
element.
The IDL attributes src
, type
, charset
, defer
, each must reflect the respective
content attributes of the same name.
The crossOrigin
IDL attribute must
reflect the crossorigin
content attribute.
The async
IDL attribute controls whether the
element will execute asynchronously or not. If the element's "non-blocking" flag is
set, then, on getting, the async
IDL attribute must return
true, and on setting, the "non-blocking" flag must first be unset, and then the
content attribute must be removed if the IDL attribute's new value is false, and must be set to
the empty string if the IDL attribute's new value is true. If the element's
"non-blocking" flag is not set, the IDL attribute must reflect
the async
content attribute.
text
[ = value ]Returns the contents of the element, ignoring child nodes that aren't Text
nodes.
Can be set, to replace the element's children with the given value.
The IDL attribute text
must return a
concatenation of the contents of all the Text
nodes that are children of the
script
element (ignoring any other nodes such as comments or elements), in tree
order. On setting, it must act the same way as the textContent
IDL attribute.
When inserted using the document.write()
method, script
elements execute (typically blocking further script execution or HTML parsing), but when inserted using
innerHTML
and outerHTML
attributes, they do not execute at all.
In this example, two script
elements are used. One embeds an external script, and
the other includes some data.
<script src="game-engine.js"></script> <script type="text/x-game-map"> ........U.........e o............A....e .....A.....AAA....e .A..AAA...AAAAA...e </script>
The data in this case might be used by the script to generate the map of a video game. The data doesn't have to be used that way, though; maybe the map data is actually embedded in other parts of the page's markup, and the data block here is just used by the site's search engine to help users who are looking for particular features in their game maps.
The following sample shows how a script element can be used to define a function that is then
used by other parts of the document. It also shows how a script
element can be used
to invoke script while the document is being parsed, in this case to initialise the form's
output.
<script> function calculate(form) { var price = 52000; if (form.elements.brakes.checked) price += 1000; if (form.elements.radio.checked) price += 2500; if (form.elements.turbo.checked) price += 5000; if (form.elements.sticker.checked) price += 250; form.elements.result.value = price; } </script> <form name="pricecalc" onsubmit="return false" onchange="calculate(this)"> <fieldset> <legend>Work out the price of your car</legend> <p>Base cost: £52000.</p> <p>Select additional options:</p> <ul> <li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li> <li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li> <li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li> <li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li> </ul> <p>Total: £<output name=result></output></p> </fieldset> <script> calculate(document.forms.pricecalc); </script> </form>
A user agent is said to support the scripting language if each component of the script block's type is an ASCII case-insensitive match for the corresponding component in the MIME type string of a scripting language that the user agent implements.
The following lists the MIME type strings that user agents must recognize, and the languages to which they refer:
application/ecmascript
application/javascript
application/x-ecmascript
application/x-javascript
text/ecmascript
text/javascript
text/javascript1.0
text/javascript1.1
text/javascript1.2
text/javascript1.3
text/javascript1.4
text/javascript1.5
text/jscript
text/livescript
text/x-ecmascript
text/x-javascript
User agents may support other MIME types for other languages, but must not support other MIME types for the languages in the list above. User agents are not required to support the languages listed above.
The following MIME types (with or without parameters) must not be interpreted as scripting languages:
These types are explicitly listed here because they are poorly-defined types that are nonetheless likely to be used as formats for data blocks, and it would be problematic if they were suddenly to be interpreted as script by a user agent.
When examining types to determine if they represent supported languages, user agents must not ignore MIME parameters. Types are to be compared including all parameters.
For example, types that include the charset
parameter will
not be recognised as referencing any of the scripting languages listed above.
script
elementsThe easiest and safest way to avoid the rather strange restrictions described in
this section is to always escape "<!--
" as "<\!--
", "<script
" as "<\script
", and "</script
" as "<\/script
" when these sequences appear in literals in scripts (e.g. in
strings, regular expressions, or comments), and to avoid writing code that uses such constructs in
expressions. Doing so avoids the pitfalls that the restrictions in this section are prone to
triggering: namely, that, for historical reasons, parsing of script
blocks in HTML is
a strange and exotic practice that acts unintuitively in the face of these sequences.
The textContent
of a script
element must match the script
production in the following ABNF, the character set for which is Unicode.
[[!ABNF]]
script = outer *( comment-open inner comment-close outer ) outer = < any string that doesn't contain a substring that matches not-in-outer > not-in-outer = comment-open inner = < any string that doesn't contain a substring that matches not-in-inner > not-in-inner = comment-close / script-open comment-open = "<!--" comment-close = "-->" script-open = "<" s c r i p t tag-end s = %x0053 ; U+0053 LATIN CAPITAL LETTER S s =/ %x0073 ; U+0073 LATIN SMALL LETTER S c = %x0043 ; U+0043 LATIN CAPITAL LETTER C c =/ %x0063 ; U+0063 LATIN SMALL LETTER C r = %x0052 ; U+0052 LATIN CAPITAL LETTER R r =/ %x0072 ; U+0072 LATIN SMALL LETTER R i = %x0049 ; U+0049 LATIN CAPITAL LETTER I i =/ %x0069 ; U+0069 LATIN SMALL LETTER I p = %x0050 ; U+0050 LATIN CAPITAL LETTER P p =/ %x0070 ; U+0070 LATIN SMALL LETTER P t = %x0054 ; U+0054 LATIN CAPITAL LETTER T t =/ %x0074 ; U+0074 LATIN SMALL LETTER T tag-end = %x0009 ; U+0009 CHARACTER TABULATION (tab) tag-end =/ %x000A ; U+000A LINE FEED (LF) tag-end =/ %x000C ; U+000C FORM FEED (FF) tag-end =/ %x0020 ; U+0020 SPACE tag-end =/ %x002F ; U+002F SOLIDUS (/) tag-end =/ %x003E ; U+003E GREATER-THAN SIGN (>)
When a script
element contains script documentation, there are
further restrictions on the contents of the element, as described in the section below.
The following script illustrates this issue. Suppose you have a script that contains a string, as in:
var example = 'Consider this string: <!-- <script>'; console.log(example);
If one were to put this string directly in a script
block, it would violate the
restrictions above:
<script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script>
The bigger problem, though, and the reason why it would violate those restrictions, is that
actually the script would get parsed weirdly: the script block above is not terminated.
That is, what looks like a "</script>
" end tag in this snippet is
actually still part of the script
block. The script doesn't execute (since it's not
terminated); if it somehow were to execute, as it might if the markup looked as follows, it would
fail because the script (highlighted here) is not valid JavaScript:
<script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script> <!-- despite appearances, this is actually part of the script still! --> <script> ... // this is the same script block still... </script>
What is going on here is that for legacy reasons, "<!--
" and "<script
" strings in script
elements in HTML need to be balanced
in order for the parser to consider closing the block.
By escaping the problematic strings as mentioned at the top of this section, the problem is avoided entirely:
<script> var example = 'Consider this string: <\!-- <\script>'; console.log(example); </script> <!-- this is just a comment between script blocks --> <script> ... // this is a new script block </script>
It is possible for these sequences to naturally occur in script expressions, as in the following examples:
if (x<!--y) { ... } if ( player<script ) { ... }
In such cases the characters cannot be escaped, but the expressions can be rewritten so that the sequences don't occur, as in:
if (x < !--y) { ... } if (!--y > x) { ... } if (!(--y) > x) { ... } if (player < script) { ... } if (script > player) { ... }
Doing this also avoids a different pitfall as well: for related historical reasons, the string "<!--" in JavaScript is actually treated as a line comment start, just like "//".
If a script
element's src
attribute is
specified, then the contents of the script
element, if any, must be such that the
value of the text
IDL attribute, which is derived from the
element's contents, matches the documentation
production in the following
ABNF, the character set for which is Unicode. [[!ABNF]]
documentation = *( *( space / tab / comment ) [ line-comment ] newline ) comment = slash star *( not-star / star not-slash ) 1*star slash line-comment = slash slash *not-newline ; characters tab = %x0009 ; U+0009 CHARACTER TABULATION (tab) newline = %x000A ; U+000A LINE FEED (LF) space = %x0020 ; U+0020 SPACE star = %x002A ; U+002A ASTERISK (*) slash = %x002F ; U+002F SOLIDUS (/) not-newline = %x0000-0009 / %x000B-10FFFF ; a Unicode character other than U+000A LINE FEED (LF) not-star = %x0000-0029 / %x002B-10FFFF ; a Unicode character other than U+002A ASTERISK (*) not-slash = %x0000-002E / %x0030-10FFFF ; a Unicode character other than U+002F SOLIDUS (/)
This corresponds to putting the contents of the element in JavaScript comments.
This requirement is in addition to the earlier restrictions on the syntax of
contents of script
elements.
This allows authors to include documentation, such as license information or API information,
inside their documents while still referring to external script files. The syntax is constrained
so that authors don't accidentally include what looks like valid script while also providing a
src
attribute.
<script src="cool-effects.js"> // create new instances using: // var e = new Effect(); // start the effect using .play, stop using .stop: // e.play(); // e.stop(); </script>
script
elements and XSLTThis section is non-normative.
This specification does not define how XSLT interacts with the script
element.
However, in the absence of another specification actually defining this, here are some guidelines
for implementors, based on existing implementations:
When an XSLT transformation program is triggered by an <?xml-stylesheet?>
processing instruction and the browser implements a
direct-to-DOM transformation, script
elements created by the XSLT processor need to
be marked "parser-inserted" and run in document order (modulo scripts marked defer
or async
),
immediately, as the transformation is occurring.
The XSLTProcessor.transformToDocument()
method
adds elements to a Document
that is not in a browsing context, and,
accordingly, any script
elements they create need to have their "already
started" flag set in the prepare a script algorithm and never get executed
(scripting is disabled). Such script
elements still need to be marked "parser-inserted", though, such that their async
IDL attribute will return false in the absence of an async
content attribute.
The XSLTProcessor.transformToFragment()
method
needs to create a fragment that is equivalent to one built manually by creating the elements
using document.createElementNS()
. For instance,
it needs to create script
elements that aren't "parser-inserted" and
that don't have their "already started" flag set, so that they will execute when the
fragment is inserted into a document.
The main distinction between the first two cases and the last case is that the first two
operate on Document
s and the last operates on a fragment.
noscript
elementhead
element of an HTML document, if there are no ancestor noscript
elements.noscript
elements.head
element: in any order, zero or more link
elements, zero or more style
elements, and zero or more meta
elements.head
element: transparent, but there must be no noscript
element descendants.HTMLElement
.The noscript
element represents nothing if scripting is enabled, and represents its children if
scripting is disabled. It is used to present different
markup to user agents that support scripting and those that don't support scripting, by affecting
how the document is parsed.
When used in HTML documents, the allowed content model is as follows:
head
element, if scripting is
disabled for the noscript
elementThe noscript
element must contain only link
, style
,
and meta
elements.
head
element, if scripting is enabled
for the noscript
elementThe noscript
element must contain only text, except that invoking the
HTML fragment parsing algorithm with
the noscript
element as the context
element and the text contents as the input must result in a list of nodes
that consists only of link
, style
, and meta
elements that
would be conforming if they were children of the noscript
element, and no parse errors.
head
elements, if scripting is
disabled for the noscript
elementThe noscript
element's content model is transparent, with the
additional restriction that a noscript
element must not have a noscript
element as an ancestor (that is, noscript
can't be nested).
head
elements, if scripting is
enabled for the noscript
elementThe noscript
element must contain only text, except that the text must be such
that running the following algorithm results in a conforming document with no
noscript
elements and no script
elements, and such that no step in the
algorithm throws an exception or causes an HTML parser to flag a parse
error:
All these contortions are required because, for historical reasons, the
noscript
element is handled differently by the HTML parser based on
whether scripting was enabled or not when the parser was
invoked.
The noscript
element must not be used in XML documents.
The noscript
element is only effective in the HTML
syntax, it has no effect in the XHTML syntax. This is because the way it works
is by essentially "turning off" the parser when scripts are enabled, so that the contents of the
element are treated as pure text and not as real elements. XML does not define a mechanism by
which to do this.
The noscript
element has no other requirements. In particular, children of the
noscript
element are not exempt from form submission, scripting, and so
forth, even when scripting is enabled for the element.
In the following example, a noscript
element is
used to provide fallback for a script.
<form action="calcSquare.php"> <p> <label for=x>Number</label>: <input id="x" name="x" type="number"> </p> <script> var x = document.getElementById('x'); var output = document.createElement('p'); output.textContent = 'Type a number; it will be squared right then!'; x.form.appendChild(output); x.form.onsubmit = function () { return false; } x.oninput = function () { var v = x.valueAsNumber; output.textContent = v + ' squared is ' + v * v; }; </script> <noscript> <input type=submit value="Calculate Square"> </noscript> </form>
When script is disabled, a button appears to do the calculation on the server side. When script is enabled, the value is computed on-the-fly instead.
The noscript
element is a blunt instrument. Sometimes, scripts might be enabled,
but for some reason the page's script might fail. For this reason, it's generally better to avoid
using noscript
, and to instead design the script to change the page from being a
scriptless page to a scripted page on the fly, as in the next example:
<form action="calcSquare.php"> <p> <label for=x>Number</label>: <input id="x" name="x" type="number"> </p> <input id="submit" type=submit value="Calculate Square"> <script> var x = document.getElementById('x'); var output = document.createElement('p'); output.textContent = 'Type a number; it will be squared right then!'; x.form.appendChild(output); x.form.onsubmit = function () { return false; } x.oninput = function () { var v = x.valueAsNumber; output.textContent = v + ' squared is ' + v * v; }; var submit = document.getElementById('submit'); submit.parentNode.removeChild(submit); </script> </form>
The above technique is also useful in XHTML, since noscript
is not supported in
the XHTML syntax.