diff --git a/images/asyncdefer.svg b/images/asyncdefer.svg index 80da42c1cf5..8c22fc50bf4 100644 --- a/images/asyncdefer.svg +++ b/images/asyncdefer.svg @@ -1,4 +1,4 @@ -
-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 type
attribute allows customization of
+ the type of script represented:
Omitting the attribute, or setting it to a JavaScript MIME type, means that
+ the script is a classic script, to be interpreted according to the JavaScript Script top-level production. Classic scripts are affected by the
+ charset
, async
, and defer
+ attributes. Authors should omit the attribute, instead of redundantly giving a JavaScript
+ MIME type.
Setting the attribute to an ASCII case-insensitive match for the string
+ "module
" means that the script is a module script, to be
+ interpreted according to the JavaScript Module top-level
+ production. Module scripts are not affected by the charset
and defer
+ attributes.
Setting the attribute to any other value means that the script is a data
+ block, which is not processed. None of the script
attributes (except type
itself) have any effect on data blocks. Authors must use
+ a valid MIME type that is not a JavaScript MIME type to denote data
+ blocks.
The requirement that data blocks must be denoted
+ using a valid MIME type is in place to avoid potential future collisions. If this
+ specification ever adds additional types of script, they will be triggered by
+ setting the type
attribute to something which is not a
+ MIME type, like how the "module
" value denotes module scripts. By using a valid MIME type now, you ensure that your data block
+ will not ever be reinterpreted as a different script type, even in future user agents.
Classic scripts and module
+ scripts may either be embedded inline or may be imported from an external file using the
+ src
attribute, which if specified gives the
+ address of the external script resource to use. If src
is
+ specified, it must be a valid non-empty URL potentially surrounded by spaces. The
+ contents of inline script
elements, or the external script resource, must conform
+ with the requirements of the JavaScript specification's Script or
+ Module productions, for classic
+ scripts and module scripts respectively.
When used to include data blocks, the data must be embedded
+ inline, the format of the data must be given using the type
attribute, and the contents of the script
+ element must conform to the requirements defined for the format used. The src
, charset
, async
, defer
, crossorigin
, and nonce
attributes must not be specified.
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
+ data-x="attr-script-src">src attribute is not present, or if the script is not a
+ classic script. (Module scripts are always
+ interpreted as UTF-8.) 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.
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. This is summarized in the following schematic diagram:
The async
and defer
attributes are boolean attributes that indicate how the script should be evaluated. Classic scripts may specify defer
or async
; module scripts may specify async
.
There are several possible modes that can be selected using these attributes, and depending on + the script's type.
+ +For classic scripts, if the async
attribute is present, then the classic script will be
+ fetched in parallel to parsing and evaluated as soon as it is available (potentially
+ before parsing completes). If the async
attribute is not
+ present but the defer
attribute is present, then the
+ classic script will be fetched in parallel and evaluated when the page has finished
+ parsing. If neither attribute is present, then the script is fetched and evaluated immediately,
+ blocking parsing until these are both complete.
For module scripts, if the async
attribute is present, then the module script and all its
+ dependencies will be fetched in parallel to parsing, and the module script will
+ be evaluated as soon as it is available (potentially before parsing completes). Otherwise, the
+ module script and its dependencies will be fetched in parallel to parsing and
+ evaluated when the page has finished parsing. (The defer
+ attribute has no effect on module scripts.)
This is all summarized in the following schematic diagram:
+ +The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation @@ -59367,9 +59424,15 @@ dictionary RelatedEventInit : EventInit { 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.
Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching.
The nonce
attribute represents a
cryptographic nonce ("number used once") which can be used by Content Security Policy
@@ -59386,6 +59449,182 @@ dictionary RelatedEventInit : EventInit {
The IDL attributes src
, type
, charset
, defer
, and nonce
, must each 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
+ classic script, and the other includes some data as a data block.
<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, as part of a classic script. 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>+ +
The following sample shows how a script
element can be used to include an
+ external module script.
+
+
<script type="module" src="app.js"></script>+ +
This module, and all its dependencies (expressed through JavaScript import
statements in the source file), will be fetched. Once the entire
+ resulting module tree has been imported, and the document has finished parsing, the contents of
+ app.js
will be evaluated.
The following sample shows how a script
element can be used to write an inline
+ module script that performs a number of substitutions on the document's text, in
+ order to make for a more interesting reading experience (e.g. on a news site):
<script type="module"> + import { walkAllTextNodeDescendants } from "./dom-utils.js"; + + const substitutions = new Map([ + ["witnesses", "these dudes I know"] + ["allegedly", "kinda probably"] + ["new study", "Tumblr post"] + ["rebuild", "avenge"] + ["space", "spaaace"] + ["Google glass", "Virtual Boy"] + ["smartphone", "Pokédex"] + ["electric", "atomic"] + ["Senator", "Elf-Lord"] + ["car", "cat"] + ["election", "eating contest"] + ["Congressional leaders", "river spirits"] + ["homeland security", "Homestar Runner"] + ["could not be reached for comment", "is guilty and everyone knows it"] + ]); + + function substitute(textNode) { + for (const [before, after] of substitutions.entries()) { + textNode.data = textNode.data.replace(new RegExp(`\\b${before}\\b`, "ig"), after); + } + } + + walkAllTextNodeDescendants(document.body, substitute); +</script>+ +
Some notable features gained by using a module script include the ability to import functions
+ from other JavaScript modules, strict mode by default, and how top-level declarations do not
+ introduce new properties onto the global object. Also note that no matter where
+ this script
element appears in the document, it will not be evaluated until both
+ document parsing has complete and its dependency (dom-utils.js
) has been
+ fetched and evaluated.
A script
element has several associated pieces of state.
The first is a flag indicating whether or not the script block has been "already
@@ -59399,11 +59638,11 @@ dictionary RelatedEventInit : EventInit {
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
+
The third is a flag indicating whether the element will be "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 an async
content attribute added, the element's
"non-blocking" flag must be unset.
The last few pieces of state are 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.
The fifth is the script's type, which is either "classic
" or "module
". It is determined when the script is
+ prepared, based on the type
attribute of the element at that time. Initially,
+ script
elements must have this flag unset.
The sixth is a flag indicating whether or not the script is from an external file. It is determined when the script is
+ prepared, based on the src
attribute of the element at that time.
Finally, a script
element has the script's
+ script, which is a script resulting from preparing the element. This is set asynchronously after the classic script or
+ module tree is fetched. Once it is set, either to a script in the case of success
+ or to null in the case of failure, the fetching algorithms will note that the script is
+ ready, which can trigger other actions. The user
+ agent must delay the load event of the element's node document until
+ the script is ready.
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
@@ -59449,7 +59704,7 @@ dictionary RelatedEventInit : EventInit {
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 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.
Text
nodes, then 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 the element is not in a Document
, then abort these steps at
+ this point. The script is not executed.
...let the script block's type for this script
element be
+
...let the script block's type string 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.
script
element
+ be the concatenation of the string "text/
" followed by the value of the
+ language
attribute.
@@ -59533,9 +59788,22 @@ dictionary RelatedEventInit : EventInit {
conforming, and is always ignored if there is a type
attribute present.
- Determine whether the the script block's type is an ASCII - case-insensitive match for any JavaScript MIME type. If this is not the - case, then the user agent must abort these steps at this point. No script is executed.
+Determine the script's type as follows:
+ +classic
".module
", the
+ script's type is "module
".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.
+Set the element's "already started" flag.
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.
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
@@ -59587,13 +59851,15 @@ dictionary RelatedEventInit : EventInit {
data-x="attr-script-src">src content attribute, and the Should element's inline
behavior be blocked by Content Security Policy? algorithm returns "Blocked
" when executed upon the script
element and "script
", then the user agent must abort these steps. The script is not executed.
-
If the script
element has an event
- attribute and a for
attribute, then run these substeps:
for
attribute, and the script's type is "classic
", then
+ run these substeps:
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.
window
", then 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.
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.
If the script
element does not have a charset
attribute, or if getting an encoding
+ failed, let encoding be the same as the
+ encoding of the document itself.
Only one of these two pieces of state is set.
+If the script's type is "module
", this encoding will be ignored.
Let CORS setting be the current state of the element's crossorigin
content attribute.
Let settings be the element's node document's
+ Window
object's environment settings object.
If the element has a src
content attribute, run these
@@ -59649,32 +59921,40 @@ dictionary RelatedEventInit : EventInit {
a simple event named error
at the element, and abort
these steps.
Set the element's from an external file + flag.
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.
Let request be the result of creating a potential-CORS request given the
- resulting parsed URL and the current state of the element's
- crossorigin
content attribute.
Switch on the script's type:
-Set request's client to the
- element's node document's Window
object's environment settings
- object and type to "script
".
classic
"Fetch a classic script given url, CORS setting, + settings, and encoding.
+Fetch request.
+module
"Fetch a module script tree given url, CORS setting, + and settings.
+The resource obtained in this fashion can be either CORS-same-origin or - CORS-cross-origin. This only affects how error reporting happens.
+When the chosen algorithm asynchronously completes, set the script's script to the result. At that time, + the script is ready.
-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 For performance reasons, user agents may start fetching the classic script or module tree
+ (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
@@ -59691,59 +59971,92 @@ dictionary RelatedEventInit : EventInit {
If the element does not have a src
content attribute,
+ run these substeps:
Then, the first of the following options that describes the situation must be followed:
+Let source text be the value of the text
IDL attribute.
Switch on the script's type:
-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
attributeclassic
"Let script be the result of creating a classic script using + source text and settings.
Set the script's script to + script.
The 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 script is ready.
The task that the networking task source - places on the task queue once fetching has completed must set the element's - "ready to be parser-executed" flag. The parser will handle executing the - script.
+module
"Let base URL be the script
element's node
+ document's document base URL.
Let script be the result of creating a module script using + source text, settings, base URL, and CORS + setting.
If this returns null, set the script's + script to null and abort these substeps; the script is ready.
src
attribute, and the element has been flagged as
+ Fetch the + descendants of script. When this asynchronously completes, set + the script's script to the result. At that + time, the script is ready.
Then, follow the first of the following options that describes the situation:
+ +classic
", and the element has a 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
attributemodule
", 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.)
Add the element 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 fetching has completed must set the element's - "ready to be parser-executed" flag. The parser will handle executing the - script.
+When the script is ready, set the element's "ready to be + parser-executed" flag. The parser will handle executing the script.
If the script's
+ type is "classic
", and the element has a 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 scripts
async
attribute
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.
+When the script is ready, set the element's "ready to be + parser-executed" flag. The parser will handle executing the script.
classic
", and the element has a src
attribute, and the element does not have an async
attribute, and the element does not have the
+ "non-blocking" flag setsrc
attribute, does not have an async
attribute, and does not have the
+ module
", and the element does not have an async
attribute, and the element 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
+
Add the element 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 fetching has completed must run the following - steps:
+When the script is ready, run the following steps:
src
- attributeclassic
", and the element has a src
attributemodule
"The 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.
script
element at the
+ time the prepare a script algorithm started.
- The task that the networking task source - places on the task queue once fetching has completed must execute the - script block and then remove the element from the set of scripts that will - execute as soon as possible.
+When the script is ready, execute the script block and then + remove the element from the set of scripts that will execute as soon as + possible.
+ +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.
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).
When the user agent is required to execute a script - block, it must run the following steps:
+ block, it must run the following 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.
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 value of the text
IDL attribute at the time
- the element's "already started" flag was last set is 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.
If the script's script is null, fire a
+ simple event named error
at the element, and abort
+ these steps.
Create a script, using the script
- block's source, the URL from which the script was obtained, 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.
+Fire a simple event named beforescriptexecute
that bubbles and is cancelable
+ at the script
element.
This is where the script is compiled and actually executed.
+If the event is canceled, then abort these steps.
-Initialise the script
element's node document's currentScript
object to old script
- element.
If the script is from an external file, or
+ the script's type is "module
",
+ then increment the ignore-destructive-writes counter of the script
+ element's node document. Let neutralised doc be that
+ Document
.
Decrement the ignore-destructive-writes counter of neutralised doc, if it was incremented in the earlier step.
+Let old script element be the value to which the script
+ element's node document's currentScript
object was most recently
+ initialised.
Fire a simple event named afterscriptexecute
that bubbles (but is not
- cancelable) at the script
element.
Initialise the script
element's node document's currentScript
object to the script
+ element.
If the script is from an external file, fire a simple event named load
at the script
element.
Let settings object be the environment settings object of the
+ script
element's node document's Window
object.
Otherwise, the script is internal; queue a task to fire a simple
- event named load
at the script
- element.
Switch on the script's type:
+classic
"Run the classic script given by the script's script.
module
"Run the module script given by the script's script.
+The IDL attributes src
, type
, charset
, defer
, and nonce
, must each 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.
- -Initialise the script
element's node document's currentScript
object to old script
+ element.
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.
Decrement the ignore-destructive-writes counter of neutralised doc, if it was incremented in the earlier step.
-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.
Fire a simple event named afterscriptexecute
that bubbles (but is not
+ cancelable) at the script
element.
<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.
+If the script's type is "classic
" and the script is
+ from an external file, fire a simple
+ event named load
at the script
+ element.
Otherwise queue a task to fire a simple event named load
at the script
element.
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 JavaScript MIME type is a MIME type string that is one of the @@ -60332,7 +60490,8 @@ 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 "//".
+ "<!--" in classic scripts is actually treated as a line + comment start, just like "//". @@ -78379,6 +78538,113 @@ dictionary DragEventInit : MouseEventInit { +When the user agent is required to set up a browsing context environment settings + object, given a JavaScript execution context execution context, it + must run the following steps:
+ +Let window be execution context's global object.
Let url be a copy of the address
+ of the Document
with which window associated.
Let settings object be a new environment settings object whose + algorithms are defined as follows:
+ +Return execution context.
+ +Return the browsing context with which window is associated.
+ +Return the event loop that is associated with the unit of related + similar-origin browsing contexts to which window's browsing + context belongs.
+ +Return the Document
with which window is currently associated.
Return the current character encoding of
+ the Document
with which window is currently associated.
Return the current base URL of the
+ Document
with which window is currently associated.
Return the origin of the Document
with which window
+ is currently associated.
Return the effective script origin of the Document
with which
+ window is currently associated.
Return url.
+ +Return the HTTPS state of the
+ Document
with which window is currently associated.
Return settings object.
Window
objectLet address be the address of the active document of the browsing context being navigated.
Create a script, using script source as the script
- source, address as the script source URL, and the environment settings
- object of the Window
object of the active document of the
- browsing context being navigated.
Let result be the return value of the code entry-point - of this script. If an exception was thrown, let result be void instead. (The result will be void also if scripting is disabled.)
- -Let result be the result of running the classic script + script. If an exception was thrown, let result be void instead. (The + result will be void also if scripting is + disabled.)
Process results: If the result of executing the script is void (there is no return
- value), then the result of obtaining the resource for the URL is a response whose
- status is 204
.
Process results: If result is void (there is no return value), then
+ the result of obtaining the resource for the URL is a response whose status is 204
.
Otherwise, the result of obtaining the resource for the URL is a response whose NavigatorOnLine {
A script has: A script is one of two possible structures. All scripts
+ have: An environment settings object, containing various settings that are shared
+ with other scripts in the same context. A classic script additionally has: A code entry-point is either a string containing a block of executable code to be evaluated,
- or a JavaScript function object. The latter case is used for event handlers. A string containing a block of executable code to be evaluated as a JavaScript Script. A module script additionally has: A Source Text Module Record representing the parsed module, ready to be
+ evaluated. 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. An environment settings object, various settings that are shared with other scripts in
- the same context. A CORS settings attribute state used to fetch imported modules. A JavaScript execution context shared by all
scripts that use this settings object, i.e. all scripts in a given
- realm. When we jump to a code-entry point, this execution context becomes the
- top of the JavaScript execution context stack, on top of which another execution
- context specific to the script in question is pushed. (This setup ensures ParseScript and ScriptEvaluation knows which Realm to use.)Definitions
-
-
+
+
+
+
+
+
+
+
+
A map of absolute URLs to values that are either a module script,
+ null, or a placeholder value "fetching
". The map must be initially
+ empty. It is used to ensure that imported JavaScript modules are only fetched, parsed, and
+ evaluated once.
This is typically a Window
object or a
WorkerGlobalScope
object.
An environment settings object's Realm is its realm execution context's Realm component.
+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.
-The script corresponding to the running execution context is the script in the [[HostDefined]] slot of the running JavaScript execution context's ScriptOrModule.
-When the user agent is required to set up a browsing context environment settings - object, given a JavaScript execution context execution context, it - must run the following steps:
+To fetch a classic script for a script
element element,
+ given a url, a CORS setting, a settings object, and a
+ character encoding, run these steps. The algorithm will asynchronously complete with
+ either null (on failure) or a new classic script (on success).
Let window be execution context's global object.
Let request be the result of creating a potential-CORS request given url and CORS + setting.
Set request's client to
+ settings object, and its type to "script
".
Fetch request.
Let url be a copy of the address
of the Document
with which window is associated.
Let settings object be a new environment settings object whose - algorithms are defined as follows:
+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.
+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.
Return execution context.
+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).
Let source text be the result of decoding + response's body to Unicode, using + character encoding as the fallback encoding.
-The decode algorithm overrides character encoding if + the file contains a BOM.
+Return the browsing context with which window is associated.
+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.
+Return the event loop that is associated with the unit of related - similar-origin browsing contexts to which window's browsing - context belongs.
+To fetch a module script tree given a url, a CORS setting, + and a settings object, run these steps. The algorithm will asynchronously complete + with either null (on failure) or a new module script (on success).
- +Fetch a single module script given url, CORS setting, + and settings object.
-Return from this algorithm and run the following steps when fetching a single module script asynchronously completes with + result:
Return the Document
with which window is currently associated.
If result is null, asynchronously complete this algorithm with null and abort + these steps.
Otherwise, result is a module script. Fetch the descendants of result.
When fetching the descendants of + a module script asynchronously completes with descendants result, + asynchronously complete this algorithm with descendants result.
Return the current character encoding of
- the Document
with which window is currently associated.
To fetch the descendants of a module script module script, run these + steps. The algorithm will asynchronously complete with either null (on failure) or with + module script (on success).
- +Let record be module script's module record.
If record.[[RequestedModules]] is empty, asynchronously complete this + algorithm with module script.
Return the current base URL of the
- Document
with which window is currently associated.
Let urls be a new empty list.
For each string requested of record.[[RequestedModules]],
-Let url be the result of resolving + a module specifier given module script and requested.
Return the origin of the Document
with which window
- is currently associated.
If the result is error:
-Let error be a new TypeError
.
Report the exception error for module + script.
Return the effective script origin of the Document
with which
- window is currently associated.
Abort this algorithm, and asynchronously complete it with null.
Otherwise, add url to urls.
For each url in urls, fetch a module script tree given + url, module script's CORS setting, and + module script's settings object.
-Return url.
+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 CORS setting, + and a settings object, run these steps. The algorithm will asynchronously complete + with either null (on failure) or a new module script (on success).
-Return the HTTPS state of the
- Document
with which window is currently associated.
Let module map be settings's module map.
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.
If module map contains an entry with key url, asynchronously + complete this algorithm with that entry's value, and abort these steps.
Create an entry in module map with key url and value "fetching
".
Let credentials mode be determined by switching on CORS setting: +
omit
"same-origin
"include
"Return settings object.
Let request be a new request whose
+ url is url, destination is "subresource
",
+ type is "script
", mode is "cors
", credentials mode is credentials
+ mode, and client is
+ settings object.
Fetch request.
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.
+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 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.
+Let source text be the result of UTF-8 + decoding response's body.
Let module script be the result of creating a module script given + source text, settings object, response's url, and CORS setting.
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.
+When a user agent is to jump to a code entry-point for a script s, given an optional rethrow errors - flag, the user agent must run the following steps:
+To create a classic script, given some script + source, an environment settings object, and an optional muted errors + flag:
Let settings be the settings object of s.
Let script be a new classic script that this algorithm will + subsequently initialise.
Set script's settings object to the environment + settings object provided.
If scripting is disabled for the given + environment settings object's responsible browsing context, then set + script's source text to the + empty string. Otherwise, set script's source text to the supplied script + source.
Assert: s's code entry-point is a string of source text; this - algorithm should never be reached when it is a function.
If the muted errors flag was set, then set script's muted + errors flag.
Prepare to run a callback with settings. If this returns "do not - run" then abort these steps.
Return script.
Let result be ParseScript(s's - code entry-point, s).
If result is a List of errors, then:
+To create a module script, given some script + source, an environment settings object, a script base URL, and a CORS settings + attribute state:
-If the rethrow errors flag is set and s's muted errors - flag is not set, rethrow the error given by the first element of result.
If the rethrow errors flag is set and s's muted
- errors flag is set, throw a NetworkError
exception.
Let script be a new module script that this algorithm will + subsequently initialise.
If the rethrow errors flag is not set, report the exception - given by the first element in result for the script s.
Set script's settings object to the environment + settings object provided.
In all cases, go to the step labeled cleanup.
Let realm be the provided environment settings object's Realm.
If scripting is disabled for the given + environment settings object's responsible browsing context, then let + script source be the empty string. Otherwise, let script source be the + provided script source.
Let result be ParseModule(script source, realm, + script).
If result is a List of errors, report the exception given by the + first element of result for script, return null, and abort these + steps.
Set script's module + record to result.
Set script's base URL to + the script base URL provided.
Set script's CORS + setting to the CORS settings attribute state provided.
Return script.
Let status be
+
+ To run a classic script given a classic script s and an
+ optional rethrow errors flag: Let settings be the settings object of s. Check if we can run script with settings. If this returns "do
+ not run" then abort these steps. Let realm be settings's Realm. Prepare to run script with settings. Let result be ParseScript(s's source text, realm,
+ s). If result is a List of errors, set result to the first element
+ of result and go to the step labeled error. Let evaluationStatus be ScriptEvaluation(result). If evaluationStatus is an abrupt completion, set result to
+ evaluationStatus.[[value]] and go to the step labeled error. If we have reached this step, skip to the step labeled cleanup. If status is an abrupt completion, then: Error: At this point result must be an error object. Perform the following
+ steps: If the rethrow errors flag is set and s's muted errors
- flag is not set, rethrow the error given by result.[[value]]. If the rethrow errors flag is set and s's muted
+ errors flag is not set, rethrow result. If the rethrow errors flag is set and s's muted
- errors flag is set, throw a If the rethrow errors flag is set and s's muted
+ errors flag is set, throw a If the rethrow errors flag is not set, report the exception
- given result.[[value]] for the script s.Calling scripts
+
+
+
+
-
NetworkError
exception.NetworkError
exception.
Cleanup: Clean up after running a callback with +
Cleanup: Clean up after running script with settings.
If result exists and is not an abrupt completion, return - result.[[value]]. Otherwise, script execution was unsuccessful, either because an - error occurred during parsing, or an exception occurred during evaluation, or because it was - aborted prematurely.
If evaluationStatus exists and is not an abrupt completion, return + evaluationStatus.[[value]]. Otherwise, script execution was unsuccessful, either + because an error occurred during parsing, or an exception occurred during evaluation, or because + it was aborted prematurely.
To run a module script given a module script s:
+ +Let settings be the settings object of s.
Check if we can run script with settings. If this returns "do + not run" then abort these steps.
Let record be s's module record.
+ +Let instantiationStatus be record.ModuleDeclarationInstantiation().
+ +This step will recursively instantiate all of the module's dependencies.
+If instantiationStatus is an abrupt completion, report the + exception given by instantiationStatus.[[value]] for s and abort + these steps.
Prepare to run script given settings.
Let evaluationStatus be record.ModuleEvaluation().
+ +This step will recursively evaluate all of the module's dependencies.
+If evaluationStatus is an abrupt completion, report the exception + given by evaluationStatus.[[value]] for s.
Clean up after running script with settings.
The steps to prepare to run a callback with an environment settings object - settings are as follows. They return either "run" or "do not run".
+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".
Return "run".
The steps to prepare to run script with + an environment settings object settings are as follows:
+ +Label settings as a candidate entry settings object.
Push settings's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.
Return "run".
The steps to clean up after running a callback with an environment settings - object settings are as follows. are as follows:
+The steps to clean up after running + script with an environment settings object settings are as + follows:
When the specification says that a script is to be created, given some script source, a script source URL, an - environment settings object, and optionally muted errors and rethrow - 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.
- -Set script's code entry-point to the supplied script - source.
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.
Jump to script's code - entry-point, passing the rethrow errors flag if it was given.
Assert: queueName is "PromiseJobs"
. ("ScriptJobs"
must not be used by user agents.)
Let settings be the settings object of the script
+ Let settings be the settings object of the script
corresponding to the running execution context. Queue a microtask, on settings's responsible event
loop, to perform the following steps: Prepare to run a callback with settings. If this returns "do
+ Check if we can run script with settings. If this returns "do
not run" then abort these steps. Prepare to run script with settings. Performing the abstract operation specified by job, using the elements of
arguments as its arguments. Clean up after running a callback with settings. Clean up after running script with settings.
-
The JavaScript specification defines a syntax for modules, as well as some host-agnostic parts
+ of their processing model. This specification defines the rest of their processing model: how the
+ module system is bootstrapped, via the script
element with type
attribute set to "module
", and how
+ modules are fetched, resolved, and executed.
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.
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.
+ +Apply the URL parser to specifier. If the result is not failure, + return the result.
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.
Return the result of applying the URL parser to specifier with + script's base URL as the base + URL.
JavaScript contains an implementation-defined HostResolveImportedModule abstract operation. User + agents must use the following implementation.
+ +Let referencing module script be + referencingModule.[[HostDefined]].
Let module map be referencing module script's settings + object's module map.
Let url be the result of resolving a
+ module specifier given referencing module script and specifier. If
+ the result is failure, throw a TypeError
exception and abort these steps.
Let resolved module script be the value of the entry in module map
+ whose key is url. If no such entry exists, or if the value is null or "fetching
", throw a TypeError
exception and abort these
+ steps.
Return resolved module script's module record.
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 + 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.
@@ -87642,15 +88223,7 @@ typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEvent -Let script be a new script.
Let script's code entry-point be function.
Let script's settings object be script - settings.
Set H's value to function.
Let script source be the first method argument.
Let settings object be method context's environment settings - object.
Let settings object be method context's environment + settings object.
Create a script using script source as the script source, - the URL where script source can be found, and settings - object as the environment settings object.
Let script be the result of creating a classic script using + script source and settings object.
Run the classic script + script.
When the user agent is to create a new MessagePort
object with a
- particular settings object as its owner, it must instantiate a
- new MessagePort
object, and let its owner be
- owner.
MessagePort
object, and let its owner
+ be owner.
When the user agent is to entangle two MessagePort
objects, it must run
the following steps:
Document
s of each
worker whose list contains that Document
.
- Given a settings object o when creating or obtaining a +
Given an environment settings object o when creating or obtaining a
worker, the list of relevant Document
objects to add depends on the type
- of global object specified by o's. If o
+ of global object specified by o. If o
specifies a global object that is a WorkerGlobalScope
object (i.e. if we
are creating a nested worker), then the relevant Document
s are the the worker's
Document
s of the global object specified by o. Otherwise, o specifies a global object that
@@ -95301,13 +95876,11 @@ interface WorkerGlobalScope : EventTarget {
-
Let script be a new script with - code entry-point source and settings object settings - object.
Let script be the result of creating a classic script using + source and settings object.
Jump to the script's code entry-point.
+Run the classic script script.
In addition to the usual possibilities of returning a value or failing due to an exception, this could be prematurely aborted by the "kill a worker" or @@ -95939,18 +96512,22 @@ interface SharedWorker : EventTarget {
Create a script using source as the script source, the - URL from which source was obtained, settings object as - the environment settings object, and passing the rethrow errors - flag.
+Let script be the result of creating a classic script using + source and settings object.
If response is CORS-cross-origin, pass the muted errors - flag to the create a script algorithm as well.
+ flag to the create a classic script algorithm + as well. + +Run the classic script script, + passing the rethrow errors flag.
-The newly created script will run until - it either returns, fails to parse, fails to catch an exception, or gets prematurely aborted - by the "kill a worker" or "terminate a worker" algorithms defined - above.
+script will run until it either returns, fails to parse, fails to + catch an exception, or gets prematurely aborted by the "kill a worker" or + "terminate a worker" algorithms defined above.
If an exception was thrown or if the script was prematurely aborted, then abort all these
steps, letting the exception or aborting continue to be processed by the calling [XHTMLMOD]