4.12. Scripting
Scripts allow authors to add interactivity to their documents.
Authors are encouraged to use declarative alternatives to scripting where possible, as declarative mechanisms are often more maintainable, and many users disable scripting.
details element could be used. Authors are also encouraged to make their applications degrade gracefully in the absence of scripting support.
4.12.1. The script#elementdef-scriptReferenced in:1.9. A quick introduction to HTML1.9.1. Writing secure applications with HTML1.10.3.
Restrictions on content models and on attribute values (2)2.2.1. Conformance classes (2) (3)3.1.3. DOM tree accessors (2) (3)3.2.4.2.1. Metadata content3.2.4.2.2. Flow content3.2.4.2.5. Phrasing content3.2.4.2.9. Script-supporting elements3.2.5.6. The dir attribute4.2.5. The meta element4.3.1. The body element4.10.10. The option element (2) (3)4.12.1. The script element (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14) (15) (16) (17) (18) (19) (20) (21) (22) (23) (24) (25) (26) (27) (28) (29) (30) (31) (32) (33) (34) (35) (36) (37) (38) (39) (40) (41) (42) (43) (44) (45) (46) (47) (48) (49) (50) (51) (52)4.12.1.2. Restrictions for contents of script elements (2) (3) (4)4.12.1.3. Inline documentation for external scripts (2) (3)4.12.1.4. Interaction of script elements and XSLT (2) (3) (4) (5)4.12.2. The noscript element (2)7.1.1. Introduction7.1.3.7. Runtime script errors (2)7.3.3. document.write()8.1.2. Elements8.1.2.4. Optional tags8.2.3.2. The stack of open elements8.2.4. Tokenization8.2.5.4.4. The "in head" insertion mode8.2.5.4.8. The "text" insertion mode (2) (3)8.2.5.5. The rules for parsing tokens in foreign content8.2.6. The end8.2.8.4. Scripts that modify the page as it is being parsed (2) (3) (4) (5)8.2.8.5. The execution of scripts that are moving across multiple documents (2) (3)8.3. Serializing HTML fragments8.4. Parsing HTML fragments9.2. Parsing XHTML documents (2)11.1. Obsolete but conforming features11.1.1. Warnings for obsolete but conforming features11.2. Non-conforming features (2) (3)11.3.4. Other elements, attributes and APIs (2)ElementsElement content categories (2) (3) (4)Attributes (2) (3) (4) (5) (6)Element InterfacesEvents (2) element
- Categories:
- Metadata content.
- Flow content.
- Phrasing content.
- Script-supporting element.
- Contexts in which this element can be used:
- Where metadata content is expected.
- Where phrasing content is expected.
- Where script-supporting elements are expected.
- Content model:
- If there is no
srcattribute, depends on the value of thetypeattribute, but must match script content restrictions. - If there is a
srcattribute, the element must be either empty or contain only script documentation that also matches script content restrictions. - Tag omission in text/html:
- Neither tag is omissible
- Content attributes:
- Global attributes
src- Address of the resourcetype- Type of embedded resourcecharset- Character encoding of the external script resourceasync- Execute script in paralleldefer- Defer script executioncrossorigin- How the element handles crossorigin requests- Allowed ARIA role attribute values:
- None
- Allowed ARIA state and property attributes:
- Global aria-* attributes
- DOM interface:
-
interface HTMLScriptElement#htmlscriptelement-htmlscriptelementReferenced in:2.2.1. Conformance classes3.1.1. The Document object11.3.4. Other elements, attributes and APIsElementsElement Interfaces : HTMLElement { attribute DOMString src; attribute DOMString type; attribute DOMString charset; attribute boolean async; attribute boolean defer; attribute DOMString? crossOrigin; attribute DOMString text; };
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#element-attrdef-script-typeReferenced in:11.1. Obsolete but conforming features (2)11.1.1. Warnings for obsolete but conforming featuresElements 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#element-attrdef-script-srcReferenced in:1.10.3.
Restrictions on content models and on attribute values (2)4.12.1.3. Inline documentation for external scriptsElements 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#element-attrdef-script-charsetReferenced in:Elements 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#element-attrdef-script-asyncReferenced in:4.12.1. The script elementElementsAttributes and defer#element-attrdef-script-deferReferenced in:4.12.1. The script elementElements 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 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 behavior instead of the blocking behavior that
is the default.
The crossorigin#element-attrdef-script-crossoriginReferenced in:4.12.1. The script elementElements 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"#already-startedReferenced in:4.12.1. The script element (2) (3) (4)4.12.1.4. Interaction of script elements and XSLT (2)8.2.5.4.4. The "in head" insertion mode8.2.5.4.8. The "text" insertion mode9.2. Parsing XHTML documents. 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"#parser-insertedReferenced in:4.12.1. The script element (2) (3) (4) (5) (6) (7) (8) (9) (10)4.12.1.4. Interaction of script elements and XSLT (2) (3)8.2.5.4.4. The "in head" insertion mode9.2. Parsing XHTML documents.
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"#non-blockingReferenced in:4.12.1. The script element (2) (3) (4) (5) (6) (7) (8)8.2.5.4.4. The "in head" insertion mode9.2. Parsing XHTML documents. 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 fourth is a flag indicating whether or not the script block is "ready to be
parser-executed"#ready-to-be-parser-executedReferenced in:4.12.1. The script element (2) (3)8.2.5.4.8. The "text" insertion mode (2)8.2.6. The end9.2. Parsing XHTML documents. 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
type, the script block character
encoding, and the script block
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:
- The
scriptelement gets inserted into a document, at the time the node is inserted according to the DOM, after any otherscriptelements inserted at the same time that are earlier in theDocumentin tree order. - The
scriptelement is in aDocumentand a node or document fragment is inserted into thescriptelement, after anyscriptelements inserted at that time. - The
scriptelement is in aDocumentand has asrcattribute set where previously the element had no such attribute.
To prepare a script#prepare-a-scriptReferenced in:4.12.1. The script element (2) (3)4.12.1.4. Interaction of script elements and XSLT, the user agent must act as follows:
-
If the
scriptelement 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
scriptelements 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
asyncattribute, then set the element’s "non-blocking" flag to true.This is done so that if a parser-inserted
scriptelement 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 theasyncattribute isn’t set. -
If the element has no
srcattribute, and its child nodes, if any, consist only of comment nodes and emptyTextnodes, 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:
- the
scriptelement has atypeattribute and its value is the empty string, or - the
scriptelement has notypeattribute but it has alanguageattribute and that attribute’s value is the empty string, or - the
scriptelement has neither atypeattribute nor alanguageattribute, then
...let the script block’s type for this
scriptelement be "text/javascript".Otherwise, if the
scriptelement has atypeattribute, let the script block’s type for thisscriptelement be the value of that attribute with any leading or trailing sequences of space characters removed.Otherwise, the element has a non-empty
languageattribute; let the script block’s type for thisscriptelement be the concatenation of the string "text/" followed by the value of thelanguageattribute.The
languageattribute is never conforming, and is always ignored if there is atypeattribute present. - the
-
If the user agent does not support the scripting language given by the script block’s type for this
scriptelement, 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
Documentof the parser that created the element, then abort these steps. -
If scripting is disabled for the
scriptelement, 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’sresponseXMLdocuments, scripts inDOMParser-created documents, scripts in documents created byXSLTProcessor’stransformToDocumentfeature, and scripts that are first inserted by a script into aDocumentthat was created using thecreateDocument()API. [XHR] [DOMPARSING] [DOM] -
If the
scriptelement has aneventattribute and aforattribute, then run these substeps:- Let for be the value of the
forattribute. - Let event be the value of the
eventattribute. - 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.
- Let for be the value of the
-
If the
scriptelement has acharsetattribute, then let the script block’s character encoding for thisscriptelement be the result of getting an encoding from the value of thecharsetattribute.Otherwise, let the script block’s fallback character encoding for this
scriptelement 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
srccontent attribute, run these substeps:- Let src be the value of the element’s
srcattribute. - If src is the empty string, queue a task to fire
a simple event named
errorat 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
errorat the element, and abort these steps. - Let request be the result of creating a potential-CORS request given the resulting absolute URL and the current state of the element’s
crossorigincontent attribute. - Set request’s client to the
element’s node document’s
Windowobject’s environment settings object and type to "script". -
Fetch request.
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
srcattribute is set, instead, in the hope that the element will be inserted into the document (and that thecrossoriginattribute 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 user agent performs such prefetching, but the element is never inserted in the document, or thesrcattribute is dynamically changed, or thecrossoriginattribute is dynamically changed, then the user agent will not execute the script so obtained, and the fetching process will have been effectively wasted.
- Let src be the value of the element’s
-
Then, the first of the following options that describes the situation must be followed:
- If the element has a
srcattribute, and the element has adeferattribute, and the element has been flagged as "parser-inserted", and the element does not have anasyncattribute -
The element must be added to the end of the list of scripts that will execute when the document has finished parsing#list-of-scripts-that-will-execute-when-the-document-has-finished-parsingReferenced in:8.2.6. The end (2) (3) (4) (5) associated with the
Documentof 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.
- If the element has a
srcattribute, and the element has been flagged as "parser-inserted", and the element does not have anasyncattribute -
The element is the pending parsing-blocking script of the
Documentof the parser that created the element. (There can only be one such script perDocumentat a time.)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.
- If the element does not have a
srcattribute, and the element has been flagged as "parser-inserted", and either the parser that created thescriptis an XML parser or it’s an HTML parser whose script nesting level is not greater than one, and theDocumentof the HTML parser or XML parser that created thescriptelement has a style sheet that is blocking scripts -
The element is the pending parsing-blocking script of the
Documentof the parser that created the element. (There can only be one such script perDocumentat a time.)Set the element’s "ready to be parser-executed" flag. The parser will handle executing the script.
- If the element has a
srcattribute, does not have anasyncattribute, and does not have the "non-blocking" flag set -
The element must be added to the end of the list of scripts that will execute in order as soon as possible#list-of-scripts-that-will-execute-in-order-as-soon-as-possibleReferenced in:4.12.1. The script element (2) (3) (4)8.2.6. The end associated with the node document of the
scriptelement 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:
- 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.
- If the element has a
srcattribute -
The element must be added to the set of scripts that will execute as soon as possible#set-of-scripts-that-will-execute-as-soon-as-possibleReferenced in:4.12.1. The script element8.2.6. The end of the node document of the
scriptelement 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.
- Otherwise
- The user agent must immediately execute the script block, even if other scripts are already executing.
- If the element has a
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#pending-parsing-blocking-scriptReferenced in:4.12.1. The script element (2) (3)7.3.2. Closing the input stream7.3.3. document.write()8.2.5.4.8. The "text" insertion mode (2) (3) (4)9.2. Parsing XHTML documents (2) (3) (4) 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#execute-a-script-blockReferenced in:4.12.1. The script element (2) (3)8.2.5.4.8. The "text" insertion mode8.2.6. The end9.2. Parsing XHTML documents, it must run the following steps:
-
If the element is flagged as "parser-inserted", but the element’s node document is not the
Documentof the parser that created the element, then abort these steps. -
Jump to the appropriate set of steps from the list below:
- If the load resulted in an error (for example a DNS error, or an HTTP 404 error)
- Executing the script block must just consist of firing a simple event named
errorat the element. - If the load was successful
-
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
scriptelement had asrcattribute specified.-
Initialize the script block’s source#is-later-usedReferenced in:4.12.1. The script element as follows:
- If the script is from an external file and the script block’s type is a text-based language
-
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.
- If the script is from an external file and the script block’s type is an XML-based language
-
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.
- If the script is inline and the script block’s type is a text-based language
-
The value of the
textIDL attribute at the time the element’s "already started" flag was last set is the script source. - If the script is inline and the script block’s type is an XML-based language
-
The child nodes of the
scriptelement at the time the element’s "already started" flag was last set are the script source.
-
Fire a simple event named
beforescriptexecutethat bubbles and is cancelable at thescriptelement.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
scriptelement’s node document. Let neutralized doc be thatDocument. -
Let old script element be the value to which the
scriptelement’s node document’scurrentScriptobject was most recently initialized. -
Initialize the
scriptelement’s node document’scurrentScriptobject to thescriptelement. -
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
scriptelement’s node document’sWindowobject.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.
-
Initialize the
scriptelement’s node document’scurrentScriptobject to old script element. -
Decrement the ignore-destructive-writes counter of neutralized doc, if it was incremented in the earlier step.
-
Fire a simple event named
afterscriptexecutethat bubbles (but is not cancelable) at thescriptelement. -
If the script is from an external file, fire a simple event named
loadat thescriptelement.Otherwise, the script is internal; queue a task to fire a simple event named
loadat thescriptelement.
-
The IDL attributes src#dom-htmlscriptelement-srcReferenced in:4.12.1. The script element, type#dom-htmlscriptelement-typeReferenced in:4.12.1. The script element, charset#dom-htmlscriptelement-charsetReferenced in:4.12.1. The script element, and defer#dom-htmlscriptelement-deferReferenced in:4.12.1. The script element, must each reflect the respective
content attributes of the same name.
The crossOrigin#dom-htmlscriptelement-crossoriginReferenced in:4.12.1. The script element IDL attribute must reflect the crossorigin content attribute.
The async#dom-htmlscriptelement-asyncReferenced in:4.12.1. The script element IDL attribute controls whether the
element will execute in parallel 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.
- script .
text[ = value ] -
Returns the contents of the element, ignoring child nodes that aren’t
Textnodes.Can be set, to replace the element’s children with the given value.
The IDL attribute text#dom-htmlscriptelement-textReferenced in:4.12.1. The script element 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.
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.
script element can be used
to invoke script while the document is being parsed, in this case to initialize 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>
4.12.1.1. Scripting languages
A user agent is said to support the scripting language#support-the-scripting-languageReferenced in:4.12.1. The script element 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.
A JavaScript MIME type#javascript-mime-typeReferenced in:4.12.1.1. Scripting languages6.6.1. Navigating across documents is a MIME type string that is one of the following and refers to JavaScript: [ECMA-262]
application/ecmascriptapplication/javascriptapplication/x-ecmascriptapplication/x-javascripttext/ecmascripttext/javascripttext/javascript1.0text/javascript1.1text/javascript1.2text/javascript1.3text/javascript1.4text/javascript1.5text/jscripttext/livescripttext/x-ecmascripttext/x-javascript
User agents must recognize all JavaScript MIME types.
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:
text/plaintext/xmlapplication/octet-streamapplication/xml
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 recognized as referencing any of the scripting languages listed above.
4.12.1.2. Restrictions for contents of script elements#script-content-restrictionsReferenced in:4.12.1. The script element (2)
The 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.
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 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 "//".
4.12.1.3. Inline documentation for external scripts#script-documentationReferenced in:4.12.1. The script element4.12.1.2. Restrictions for contents of script elements
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.
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>
4.12.1.4. Interaction of script elements and XSLT
This 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,scriptelements created by the XSLT processor need to be marked "parser-inserted" and run in document order (modulo scripts markeddeferorasync), immediately, as the transformation is occurring. - The
XSLTProcessor.transformToDocument()method adds elements to aDocumentthat is not in a browsing context, and, accordingly, anyscriptelements they create need to have their "already started" flag set in the prepare a script algorithm and never get executed (scripting is disabled). Suchscriptelements still need to be marked "parser-inserted", though, such that theirasyncIDL attribute will return false in the absence of anasynccontent attribute. - The
XSLTProcessor.transformToFragment()method needs to create a fragment that is equivalent to one built manually by creating the elements usingdocument.createElementNS(). For instance, it needs to createscriptelements 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 Documents and the last operates on a fragment.
4.12.2. The noscript#elementdef-noscriptReferenced in:1.6. HTML vs XHTML3.2.4.2.1. Metadata content3.2.4.2.2. Flow content3.2.4.2.5. Phrasing content4.2.4. The link element4.2.5. The meta element4.2.6. The style element4.4.1. The p element4.12.2. The noscript element (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14) (15) (16) (17) (18) (19) (20) (21) (22) (23) (24) (25) (26) (27) (28) (29)8.1.2.4. Optional tags8.2.3.2. The stack of open elements8.2.5.4.5. The "in head noscript" insertion mode (2)8.3. Serializing HTML fragments8.4. Parsing HTML fragmentsElements (2) (3) (4)Element content categories (2) (3)Element Interfaces element
- Categories:
- Metadata content.
- Flow content.
- Phrasing content.
- Contexts in which this element can be used:
- In a
headelement of an HTML document, if there are no ancestornoscriptelements. - Where phrasing content is expected in HTML documents, if there are no ancestor
noscriptelements. - Content model:
- When scripting is disabled, in a
headelement: in any order, zero or morelinkelements, zero or morestyleelements, and zero or moremetaelements. - When scripting is disabled, not in a
headelement: transparent, but there must be nonoscriptelement descendants. - Otherwise: text that conforms to the requirements given in the prose.
- Tag omission in text/html:
- Neither tag is omissible
- Content attributes:
- Global attributes
- Allowed ARIA role attribute values:
- None
- Allowed ARIA state and property attributes:
- Global aria-* attributes
- DOM interface:
- Uses
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:
- In a
headelement, if scripting is disabled for thenoscriptelement - The
noscriptelement must contain onlylink,style, andmetaelements. - In a
headelement, if scripting is enabled for thenoscriptelement - The
noscriptelement must contain only text, except that invoking the HTML fragment parsing algorithm with thenoscriptelement as the context element and the text contents as the input must result in a list of nodes that consists only oflink,style, andmetaelements that would be conforming if they were children of thenoscriptelement, and no parse errors. - Outside of
headelements, if scripting is disabled for thenoscriptelement - The
noscriptelement’s content model is transparent, with the additional restriction that anoscriptelement must not have anoscriptelement as an ancestor (that is,noscriptcan’t be nested). - Outside of
headelements, if scripting is enabled for thenoscriptelement -
The
noscriptelement must contain only text, except that the text must be such that running the following algorithm results in a conforming document with nonoscriptelements and noscriptelements, and such that no step in the algorithm throws an exception or causes an HTML parser to flag a parse error:- Remove every
scriptelement from the document. -
Make a list of every
noscriptelement in the document. For everynoscriptelement in that list, perform the following steps:- Let s be the concatenation of all the
Textnode children of thenoscriptelement. - Set the
outerHTMLattribute of thenoscriptelement to the value of s. (This, as a side-effect, causes thenoscriptelement to be removed from the document.) [DOMPARSING]
- Let s be the concatenation of all the
- Remove every
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 §4.10.22 Form submission, scripting, and so
forth, even when scripting is enabled for the element.
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.
4.12.3. The template#elementdef-templateReferenced in:3.2.4. Content models3.2.4.2.1. Metadata content3.2.4.2.2. Flow content3.2.4.2.5. Phrasing content3.2.4.2.9. Script-supporting elements4.3.1. The body element4.7.16. The area element (2)4.9.3. The colgroup element4.12.3. The template element (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13)4.12.3.1. Interaction of template elements with XSLT and XPath (2) (3)8.1.2.4. Optional tags8.2.3.1. The insertion mode (2)8.2.3.2. The stack of open elements (2) (3)8.2.3.4. The element pointers8.2.5.1. Creating and inserting nodes (2)8.2.5.4.4. The "in head" insertion mode (2)8.2.5.4.7. The "in body" insertion mode (2) (3) (4) (5) (6) (7)8.2.5.4.9. The "in table" insertion mode (2)8.2.5.4.13. The "in table body" insertion mode8.2.5.4.14. The "in row" insertion mode8.2.5.4.18. The "in template" insertion mode8.2.7. Coercing an HTML DOM into an infoset8.3. Serializing HTML fragments (2)8.4. Parsing HTML fragments9.2. Parsing XHTML documents (2)9.3. Serializing XHTML fragmentsElements (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14) (15) (16) (17) (18) (19) (20) (21) (22) (23) (24) (25) (26) (27) (28) (29) (30) (31)Element content categories (2) (3) (4)Element Interfaces element
- Categories:
- Metadata content.
- Flow content.
- Phrasing content.
- Script-supporting element.
- Contexts in which this element can be used:
- Where metadata content is expected.
- Where phrasing content is expected.
- Where script-supporting elements are expected.
- As a child of a
colgroupelement that doesn’t have aspanattribute. - Content model:
- Either: Metadata content.
- Or: Flow content.
- Or: The content model of
olandulelements. - Or: The content model of
dlelements. - Or: The content model of
figureelements. - Or: The content model of
rubyelements. - Or: The content model of
objectelements. - Or: The content model of
videoandaudioelements. - Or: The content model of
tableelements. - Or: The content model of
colgroupelements. - Or: The content model of
thead,tbody, andtfootelements. - Or: The content model of
trelements. - Or: The content model of
fieldsetelements. - Or: The content model of
selectelements. - Or: The content model of
detailselements. - Or: The content model of
menuelements whosetypeattribute is in the popup menu state. - Tag omission in text/html:
- Neither tag is omissible
- Content attributes:
- Global attributes
- Allowed ARIA role attribute values:
- None
- Allowed ARIA state and property attributes:
- Global aria-* attributes
- DOM interface:
-
interface HTMLTemplateElement#htmltemplateelement-htmltemplateelementReferenced in:ElementsElement Interfaces : HTMLElement { readonly attribute DocumentFragment content; };
The template element is used to declare fragments of HTML that can be cloned and
inserted in the document by script.
Templates provide a method for declaring inert DOM subtrees and manipulating them to instantiate document fragments with identical contents.
When web pages dynamically alter the contents of their documents (e.g., in response to user interaction or new data arriving from the server), it is common that they require fragments of HTML which may require further modification before use, such as the insertion of values appropriate for the usage context.
The template element allows for the declaration of document fragments which are
unused by the document when loaded, but are parsed as HTML and are available at runtime for use by
the web page.
In a rendering, the template element represents nothing.
- template .
content -
Returns the contents of the
template, which are stored in aDocumentFragmentassociated with a differentDocumentso as to avoid thetemplatecontents interfering with the mainDocument. (For example, this avoids form controls from being submitted, scripts from executing, and so forth.)
Each template element has an associated DocumentFragment object that
is its template contents#template-contentsReferenced in:3.2.4. Content models4.12.3. The template element (2) (3) (4) (5) (6) (7) (8)4.12.3.1. Interaction of template elements with XSLT and XPath (2) (3)8.2.5.1. Creating and inserting nodes (2)8.2.7. Coercing an HTML DOM into an infoset8.3. Serializing HTML fragments9.2. Parsing XHTML documents9.3. Serializing XHTML fragments. When a template element is created, the user
agent must run the following steps to establish the template contents:
- Let doc be the
templateelement’s node document’s appropriate template contents owner document. - Create a
DocumentFragmentobject whose node document is doc. - Set the
templateelement’s template contents to the newly createdDocumentFragmentobject.
A Document doc’s appropriate template contents owner
document#appropriate-template-contents-owner-documentReferenced in:4.12.3. The template element (2) is the Document returned by the following algorithm:
-
If doc is not a
Documentcreated by this algorithm, run these substeps:-
If doc does not yet have an associated inert template document#associated-inert-template-documentReferenced in:4.12.3. The template element (2) then run these substeps:
- Let new doc be a new
Document(that does not have a browsing context). This is "aDocumentcreated by this algorithm" for the purposes of the step above. - If doc is an HTML document, mark new doc as an HTML document also.
- Let doc’s associated inert template document be new doc.
- Let new doc be a new
- Set doc to doc’s associated inert template document.
Each
Documentnot created by this algorithm thus gets a singleDocumentto act as its proxy for owning the template contents of all itstemplateelements, so that they aren’t in a browsing context and thus remain inert (e.g., scripts do not run). Meanwhile,templateelements insideDocumentobjects that are created by this algorithm just reuse the sameDocumentowner for their contents. -
- Return doc.
The adopting steps (with node and oldDocument as parameters) for template elements
are the following:
-
Let doc be node’s node document’s appropriate template contents owner document.
node’s node document is the
Documentobject that node was just adopted into. - Adopt node’s template contents (a
DocumentFragmentobject) into doc.
The content IDL attribute must return the template element’s template contents.
The cloning steps for a template element node being cloned to a copy copy must run the
following steps:
- If the clone children flag is not set in the calling clone algorithm, abort these steps.
- Let copied contents be the result of cloning all the children of node’s template contents, with document set to copy’s template contents’s node document, and with the clone children flag set.
- Append copied contents to copy’s template contents.
template to provide the element structure instead of manually generating the
structure from markup.
<!DOCTYPE html> <title>Cat data</title> <script> // Data is hard-coded here, but could come from the server var data = [ { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 }, { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 }, ]; </script> <table> <thead> <tr> <th>Name <th>Color <th>Sex <th>Legs <tbody> <template id="row"> <tr><td><td><td><td> </template> </table> <script> var template = document.querySelector('#row'); for (var i = 0; i < data.length; i += 1) { var cat = data[i]; var clone = template.content.cloneNode(true); var cells = clone.querySelectorAll('td'); cells[0].textContent = cat.name; cells[1].textContent = cat.color; cells[2].textContent = cat.sex; cells[3].textContent = cat.legs; template.parentNode.appendChild(clone); } </script>
This example uses cloneNode() on the template’s contents; it could
equivalently have used document.importNode(), which does the same thing. The only
difference between these two APIs is when the node document is updated: with cloneNode() it is updated when the nodes are appended with appendChild(), with document.importNode() it is updated when the nodes
are cloned.
4.12.3.1. Interaction of template elements with XSLT and XPath
This section is non-normative.
This specification does not define how XSLT and XPath interact with the template element. However, in the absence of another specification actually defining this, here are some
guidelines for implementors, which are intended to be consistent with other processing described
in this specification:
- An XSLT processor based on an XML parser that acts as described
in this specification needs to act as if
templateelements contain as descendants their template contents for the purposes of the transform. - An XSLT processor that outputs a DOM needs to ensure that nodes that would go into a
templateelement are instead placed into the element’s template contents. - XPath evaluation using the XPath DOM API when applied to a
Documentparsed using the HTML parser or the XML parser described in this specification needs to ignore template contents.
4.12.4. The canvas#elementdef-canvasReferenced in:3.2.4.2.2. Flow content3.2.4.2.5. Phrasing content3.2.4.2.6. Embedded content3.2.4.2.8. Palpable content (2)3.2.4.4. Paragraphs4.7.5. The img element4.7.14.7. Ready states4.12.4. The canvas element (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14) (15) (16) (17) (18) (19) (20) (21) (22) (23) (24) (25) (26) (27) (28) (29) (30) (31) (32) (33) (34) (35) (36) (37) (38) (39) (40)4.12.4.1. Proxying canvases to workers (2) (3) (4) (5) (6) (7)4.12.4.2. Color spaces and color correction (2)4.12.4.4. Security with canvas elements (2) (3) (4) (5)5.1. The hidden attribute (2)5.3. Activation7.7. Images (2) (3) (4) (5)10.4.1. Embedded content (2) (3)ElementsElement content categories (2) (3) (4)Attributes (2)Element InterfacesAcknowledgements element
- Categories:
- Flow content.
- Phrasing content.
- Embedded content.
- Palpable content.
- Contexts in which this element can be used:
- Where embedded content is expected.
- Content model:
- Transparent.
- Tag omission in text/html:
- Neither tag is omissible
- Content attributes:
- Global attributes
width- Horizontal dimensionheight- Vertical dimension- Allowed ARIA role attribute values:
- Any role value.
- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*attributes applicable to the allowed roles. - DOM interface:
-
typedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext#typedefdef-htmlcanvaselement-renderingcontextReferenced in:4.12.4. The canvas element (2)4.12.4.1. Proxying canvases to workers; interface HTMLCanvasElement#htmlcanvaselement-htmlcanvaselementReferenced in:7.7. ImagesElementsElement Interfaces : HTMLElement { attribute unsigned long width; attribute unsigned long height; RenderingContext? getContext(DOMString contextId, any... arguments); boolean probablySupportsContext(DOMString contextId, any... arguments); void setContext(RenderingContext context); CanvasProxy transferControlToProxy(); DOMString toDataURL(optional DOMString type, any... arguments); void toBlob(BlobCallback _callback, optional DOMString type, any... arguments); }; callback BlobCallback#callbackdef-htmlcanvaselement-blobcallbackReferenced in:4.12.4. The canvas element = void (Blob? blob);
The canvas element provides scripts with a resolution-dependent bitmap canvas,
which can be used for rendering graphs, game graphics, art, or other visual images on the fly.
Authors should not use the canvas element in a document when a more suitable
element is available. For example, it is inappropriate to use a canvas element to
render a page heading: if the desired presentation of the heading is graphically intense, it
should be marked up using appropriate elements (typically h1) and then styled using
CSS and supporting technologies such as Web Components.
When authors use the canvas element, they must also provide content that, when
presented to the user, conveys essentially the same function or purpose as the canvas' bitmap. This content may be placed as content of the canvas element. The contents of the canvas element, if any, are the element’s fallback
content.
In interactive visual media, if scripting is enabled for
the canvas element, and if support for canvas elements has been enabled,
the canvas element represents embedded content consisting
of a dynamically created image, the element’s bitmap.
In non-interactive, static, visual media, if the canvas element has been
previously associated with a rendering context (e.g., if the page was viewed in an interactive
visual medium and is now being printed, or if some script that ran during the page layout process
painted on the element), then the canvas element represents embedded content with the element’s current bitmap and size. Otherwise, the element
represents its fallback content instead.
In non-visual media, and in visual media if scripting is
disabled for the canvas element or if support for canvas elements
has been disabled, the canvas element represents its fallback
content instead.
When a canvas element represents embedded content, the
user can still focus descendants of the canvas element (in the fallback
content). When an element is focused, it is the target of keyboard interaction
events (even though the element itself is not visible). This allows authors to make an interactive
canvas keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable areas in the fallback content. (Focus has no
effect on mouse interaction events.) [UIEVENTS]
An element whose nearest canvas element ancestor is being rendered and represents embedded content is an element that is being used as
relevant canvas fallback content#being-used-as-relevant-canvas-fallback-contentReferenced in:5.4.2. Data model.
The canvas element has two attributes to control the size of the element’s bitmap: width#element-attrdef-canvas-widthReferenced in:Elements and height#element-attrdef-canvas-heightReferenced in:Elements. These attributes, when specified, must have
values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their
numeric values. If an attribute is missing, or if parsing its value returns an error, then the
default value must be used instead. The width attribute defaults to 300, and the height attribute
defaults to 150.
The intrinsic dimensions of the canvas element when it represents embedded content are equal to the dimensions of the
element’s bitmap.
The user agent must use a square pixel density consisting of one pixel of image data per
coordinate space unit for the bitmaps of a canvas and its rendering contexts.
A canvas element can be sized arbitrarily by a style sheet, its
bitmap is then subject to the object-fit CSS property. [CSS3-IMAGES]
The bitmaps of canvas elements, the bitmaps of ImageBitmap objects,
as well as some of the bitmaps of rendering contexts, such as those described in the section on
the CanvasRenderingContext2D object below, have an origin-clean#canvas-origin-cleanReferenced in:4.12.4. The canvas element (2) (3)4.12.4.4. Security with canvas elements (2) (3) (4) (5)7.7. Images (2) (3) (4) (5) (6) (7) (8) flag, which can be set to true or false.
Initially, when the canvas element or ImageBitmap object is created,
its bitmap’s origin-clean flag must be set to
true.
A canvas bitmap can also have a hit region list, as described in the CanvasRenderingContext2D section below.
A canvas element can have a rendering context bound to it. Initially, it does not
have a bound rendering context. To keep track of whether it has a rendering context or not, and
what kind of rendering context it is, a canvas also has a canvas context mode#modedef-canvas-context-modeReferenced in:4.12.4. The canvas element (2) (3) (4) (5) (6) (7)4.12.4.1. Proxying canvases to workers (2), which is initially none#contextdef-canvas-noneReferenced in:4.12.4. The canvas element (2) (3)4.12.4.1. Proxying canvases to workers but can be changed to either direct-2d#contextdef-canvas-direct-2dReferenced in:4.12.4. The canvas element (2) (3), direct-webgl#contextdef-canvas-direct-webglReferenced in:4.12.4. The canvas element (2), indirect#contextdef-canvas-indirectReferenced in:4.12.4. The canvas element (2) (3), or proxied#contextdef-canvas-proxiedReferenced in:4.12.4. The canvas element4.12.4.1. Proxying canvases to workers by algorithms defined in this specification.
When its canvas context mode is none, a canvas element has no rendering context,
and its bitmap must be fully transparent black with an intrinsic width equal to the numeric value
of the element’s width attribute and an intrinsic height equal to the numeric value of the element’s height attribute, those values being interpreted in CSS pixels, and being updated as the attributes are
set, changed, or removed.
When a canvas element represents embedded content, it provides
a paint source whose width is the element’s intrinsic width, whose height is
the element’s intrinsic height, and whose appearance is the element’s bitmap.
Whenever the width and height content attributes are set, removed, changed, or
redundantly set to the value they already have, if the canvas context mode is direct-2d, the user agent must set bitmap dimensions to the numeric values of
the width and height content attributes.
The width#dom-htmlcanvaselement-widthReferenced in:4.12.4. The canvas element and height#dom-htmlcanvaselement-heightReferenced in:4.12.4. The canvas element IDL attributes must reflect the
respective content attributes of the same name, with the same defaults.
- context = canvas .
getContext(contextId [, ... ] ) -
Returns an object that exposes an API for drawing on the canvas. The first argument specifies the desired API, either "
2d" or "webgl". Subsequent arguments are handled by that API.The list of defined contexts is given on the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]
Example contexts are the "
2d" [CANVAS-2D] and the "webgl" context [WEBGL].Returns null if the given context ID is not supported or if the canvas has already been initialized with some other (incompatible) context type (e.g., trying to get a "
2d" context after getting a "webgl" context).Throws an
InvalidStateErrorexception if thesetContext()ortransferControlToProxy()methods have been used. - supported = canvas .
probablySupportsContext(contextId [, ... ] ) -
Returns false if calling
getContext()with the same arguments would definitely return null, and true otherwise.This return value is not a guarantee that
getContext()will or will not return an object, as conditions (e.g., availability of system resources) can vary over time.Throws an
InvalidStateErrorexception if thesetContext()ortransferControlToProxy()methods have been used. - canvas .
setContext(context) -
Sets the
canvas' rendering context to the given object.Throws an
InvalidStateErrorexception if thegetContext()ortransferControlToProxy()methods have been used.
There are two ways for a canvas element to acquire a rendering context: the canvas element can provide one via the getContext() method, and one can be assigned to it via the setContext() method. In addition, the whole issue of a
rendering context can be taken out of the canvas element’s hands and passed to a CanvasProxy object, which itself can then be assigned a rendering context using its setContext() method.
These three methods are mutually exclusive; calling any of the three makes the other two start
throwing InvalidStateError exceptions when called.
Each rendering context has a context bitmap mode#canvas-context-bitmap-modeReferenced in:4.12.4. The canvas element (2) (3) (4) (5) (6)4.12.4.1. Proxying canvases to workers (2) (3) (4), which is one of fixed#contextdef-canvas-fixedReferenced in:4.12.4. The canvas element (2) (3)4.12.4.1. Proxying canvases to workers, unbound#contextdef-canvas-unboundReferenced in:4.12.4. The canvas element (2)4.12.4.1. Proxying canvases to workers, or bound#contextdef-canvas-boundReferenced in:4.12.4. The canvas element (2)4.12.4.1. Proxying canvases to workers (2). Initially, rendering contexts must be in the unbound mode.
The getContext(contextId, arguments...)#dom-htmlcanvaselement-getcontextReferenced in:4.12.4. The canvas element method of the canvas element, when invoked,
must run the steps in the cell of the following table whose column header describes the canvas element’s canvas context mode and whose row header describes the method’s first argument.
| none | direct-2d | direct-webgl | indirect | proxied | |
|---|---|---|---|---|---|
"2d#2dReferenced in:8.2.8.1. Misnested tags: <b><i></b></i> (2)8.2.8.2. Misnested tags: <b><p></b></p> (2) (3) (4) (5)"
|
Set the | Return the same object as was return the last time the method was invoked with this same first argument. | Return null. | Throw an InvalidStateError exception.
| Throw an InvalidStateError exception.
|
"webgl", if the user agent supports the WebGL feature in its current configuration
| Follow the instructions given in the WebGL specification’s Context Creation section to
obtain either a WebGLRenderingContext or null; if the returned value is null,
then return null and abort these steps, otherwise, set the canvas element’s context mode to direct-webgl, set the new WebGLRenderingContext object’s context bitmap mode to fixed, and return the WebGLRenderingContext object‡ [WEBGL]
| Return null. | Return the same object as was return the last time the method was invoked with this same first argument. | Throw an InvalidStateError exception.
| Throw an InvalidStateError exception.
|
| A vendor-specific extension* | Behave as defined for the extension. | Behave as defined for the extension. | Behave as defined for the extension. | Throw an InvalidStateError exception.
| Throw an InvalidStateError exception.
|
| An unsupported value† | Return null. | Return null. | Return null. | Throw an InvalidStateError exception.
| Throw an InvalidStateError exception.
|
* Vendors may define experimental contexts using the syntax vendorname-context, for example, moz-3d.
† For example, the "webgl" value in the case of a user agent having exhausted the
graphics hardware’s abilities and having no software fallback implementation.
‡ The second (and subsequent) argument(s) to the method, if any, are ignored in all cases except this one. See the WebGL specification for details.
The probablySupportsContext(contextId, arguments...)#dom-htmlcanvaselement-probablysupportscontextReferenced in:4.12.4. The canvas element method of the canvas element, when
invoked, must return false if calling getContext() on
the same object and with the same arguments would definitely return null at this time, and true
otherwise.
The setContext(context)#dom-htmlcanvaselement-setcontextReferenced in:4.12.4. The canvas element method of the canvas element, when invoked, must
run the following steps:
- If the
canvaselement’s canvas context mode is neither none nor indirect, throw anInvalidStateErrorexception and abort these steps. - If context’s context
bitmap mode is fixed, then throw an
InvalidStateErrorexception and abort these steps. - If context’s context bitmap mode is bound, then run context’s unbinding steps and set its context’s context bitmap mode to unbound.
- Run context’s binding steps to bind it to this
canvaselement. - Set the
canvaselement’s context mode to indirect and the context’s context bitmap mode to bound.
- url = canvas .
toDataURL( [ type, ... ] ) -
Returns a
data:URL for the image in the canvas.The first argument, if provided, controls the type of the image to be returned (e.g., PNG or JPEG). The default is
image/png; that type is also used if the given type isn’t supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.When trying to use types other than "
image/png", authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported. (The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".) - canvas .
toBlob(callback [, type, ... ] ) -
Creates a
Blobobject representing a file containing the image in the canvas, and invokes a callback with a handle to that object.The second argument, if provided, controls the type of the image to be returned (e.g., PNG or JPEG). The default is
image/png; that type is also used if the given type isn’t supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.
The toDataURL() method must run the
following steps:
- If the
canvaselement’s bitmap’s origin-clean flag is set to false, throw aSecurityErrorexception and abort these steps. - If the
canvaselement’s bitmap has no pixels (i.e., either its horizontal dimension or its vertical dimension is zero) then return the string "data:," and abort these steps. (This is the shortestdata:URL; it represents the empty string in atext/plainresource.) - Let file be a serialization of the
canvaselement’s bitmap as a file, using the method’s arguments (if any) as the arguments. - Return a
data:URL representing file. [RFC2397]
The toBlob() method must run the following
steps:
- If the
canvaselement’s bitmap’s origin-clean flag is set to false, throw aSecurityErrorexception and abort these steps. - Let callback be the first argument.
- Let arguments be the second and subsequent arguments to the method, if any.
-
If the
canvaselement’s bitmap has no pixels (i.e., either its horizontal dimension or its vertical dimension is zero) then let result be null.Otherwise, let result be a
Blobobject representing a serialization of thecanvaselement’s bitmap as a file, using arguments. [FILEAPI] - Return, but continue running these steps in parallel.
- Queue a task to invoke the
BlobCallbackcallback with result as its argument. The task source for this task is the canvas blob serialization task source.
4.12.4.1. Proxying canvases to workers
Since DOM nodes cannot be accessed across worker boundaries, a proxy object is needed to enable
workers to render to canvas elements in Documents.
[Exposed=(Window, Worker)]
interface CanvasProxy#canvasproxy-canvasproxyReferenced in:2.7.5. Transferable objects (2)4.12.4. The canvas element {
void setContext(RenderingContext context);
};
// CanvasProxy implements Transferable;
- canvasProxy = canvas .
transferControlToProxy() -
Returns a
CanvasProxyobject that can be used to transfer control for this canvas over to another document (e.g., aniframefrom another origin) or to a worker.Throws an
InvalidStateErrorexception if thegetContext()orsetContext()methods have been used. - canvasProxy .
setContext(context) -
Sets the
CanvasProxyobject’scanvaselement’s rendering context to the given object.Throws an
InvalidStateErrorexception if theCanvasProxyhas been transferred.
The transferControlToProxy() method of the canvas element, when invoked, must run the following steps:
- If the
canvaselement’s canvas context mode is not none, throw anInvalidStateErrorexception and abort these steps. - Set the
canvaselement’s context mode to proxied. - Return a
CanvasProxyobject bound to thiscanvaselement.
A CanvasProxy object can be neutered (like any Transferable object),
meaning it can no longer be transferred, and
can be disabled#canvas-disabledReferenced in:4.12.4.1. Proxying canvases to workers, meaning it can no longer be bound
to rendering contexts. When first created, a CanvasProxy object must be neither.
A CanvasProxy is created with a link to a canvas element. A CanvasProxy object that has not been disabled must have a strong reference to its canvas
element.
The setContext(context) method of CanvasProxy objects, when invoked,
must run the following steps:
- If the
CanvasProxyobject has been disabled, throw anInvalidStateErrorexception and abort these steps. - If the
CanvasProxyobject has not been neutered, then neuter it. - If context’s context
bitmap mode is fixed, then throw an
InvalidStateErrorexception and abort these steps. - If context’s context bitmap mode is bound, then run context’s unbinding steps and set its context’s context bitmap mode to unbound.
- Run context’s binding steps to bind it to this
CanvasProxyobject’scanvaselement. - Set the context’s context bitmap mode to bound.
To transfer a CanvasProxy object old to a new owner owner,
a user agent must create a new CanvasProxy object linked to the same canvas element as old, thus obtaining new,
must neuter and disable the old object, and must
finally return new.
<!DOCTYPE HTML> <title>Clock</title> <canvas></canvas> <script> var canvas = document.getElementsByTagName('canvas')[0]; var proxy = canvas.transferControlToProxy(); var worker = new Worker('clock.js'); worker.postMessage(proxy, [proxy]); </script>
Second, the worker:
onmessage = function (event) { var context = new CanvasRenderingContext2D(); event.data.setContext(context); // event.data is the CanvasProxy object setInterval(function () { context.clearRect(0, 0, context.width, context.height); context.fillText(new Date(), 0, 100); context.commit(); }, 1000); };
4.12.4.2. Color spaces and color correction
The canvas APIs must perform color correction at only two points: when rendering
images with their own gamma correction and color space information onto a bitmap, to convert the
image to the color space used by the bitmaps (e.g., using the 2D Context’s drawImage() method with an HTMLImageElement object), and when rendering the actual canvas bitmap to the output device.
Thus, in the 2D context, colors used to draw shapes onto the canvas will exactly
match colors obtained through the getImageData() method.
The toDataURL() method must not include color space
information in the resources they return. Where the output format allows it, the color of pixels
in resources created by toDataURL() must match those
returned by the getImageData() method.
In user agents that support CSS, the color space used by a canvas element must
match the color space used for processing any colors for that element in CSS.
The gamma correction and color space information of images must be handled in such a way that
an image rendered directly using an img element would use the same colors as one
painted on a canvas element that is then itself rendered. Furthermore, the rendering
of images that have no color correction information (such as those returned by the toDataURL() method) must be rendered with no color
correction.
Thus, in the 2D context, calling the drawImage() method to render the output of the toDataURL() method to the canvas, given the appropriate
dimensions, has no visible effect.
4.12.4.3. Serializing bitmaps to a file
When a user agent is to create a serialization of the bitmap as a file#a-serialization-of-the-canvas-elements-bitmap-as-a-fileReferenced in:4.12.4. The canvas element (2), optionally with some given arguments, and optionally with a native flag set, it must create an image file in the format given by the first value of arguments, or, if there are no arguments, in the PNG format. [PNG]
If the native flag is set, or if the bitmap has one pixel per coordinate space unit, then the image file must have the same pixel data (before compression, if applicable) as the bitmap, and if the file format used supports encoding resolution metadata, the resolution of that bitmap (device pixels per coordinate space units being interpreted as image pixels per CSS pixel) must be given as well.
Otherwise, the image file’s pixel data must be the bitmap’s pixel data scaled to one image pixel per coordinate space unit, and if the file format used supports encoding resolution metadata, the resolution must be given as 96dpi (one image pixel per CSS pixel).
If arguments is not empty, the first value must be interpreted as a MIME type giving the format to use. If the type has any parameters, it must be treated as not supported.
For example, the value "image/png" would mean to generate a PNG
image, the value "image/jpeg" would mean to generate a JPEG image, and the value
"image/svg+xml" would mean to generate an SVG image (which would require that the
user agent track how the bitmap was generated, an unlikely, though potentially awesome,
feature).
User agents must support PNG ("image/png"). User agents may support other types.
If the user agent does not support the requested type, it must create the file using the PNG
format. [PNG]
User agents must convert the provided type to ASCII lowercase before establishing if they support that type.
For image types that do not support an alpha channel, the serialized image must be the bitmap image composited onto a solid black background using the source-over operator.
If the first argument in arguments gives a type corresponding to one of the types given in the first column of the following table, and the user agent supports that type, then the subsequent arguments, if any, must be treated as described in the second cell of that row.
| Type | Other arguments | Reference |
|---|---|---|
image/jpeg
| The second argument, if it is a number in the range 0.0 to 1.0 inclusive, must be treated as the desired quality level. If it is not a number or is outside that range, the user agent must use its default value, as if the argument had been omitted. | [JPEG] |
For the purposes of these rules, an argument is considered to be a number if it is converted to
an IDL double value by the rules for handling arguments of type any in the
Web IDL specification. [WEBIDL]
Other arguments must be ignored and must not cause the user agent to throw an exception. A future version of this specification will probably define other parameters to be passed to these methods to allow authors to more carefully control compression settings, image metadata, etc.
4.12.4.4. Security with canvas elements
This section is non-normative.
Information leakage can occur if scripts from one origin can access information (e.g., read pixels) from images from another origin (one that isn’t the same).
To mitigate this, bitmaps used with canvas elements and ImageBitmap objects are defined to have a flag indicating whether they are origin-clean. All bitmaps start with their origin-clean set to true. The flag is set to
false when cross-origin images or fonts are used.
The toDataURL(), toBlob(), and getImageData() methods check the flag and will
throw a SecurityError exception rather than leak cross-origin data.
The value of the origin-clean flag is
propagated from a source canvas element’s bitmap to a new ImageBitmap object by createImageBitmap(). Conversely, a
destination canvas element’s bitmap will have its origin-clean flags set to false by drawImage if the source image is an ImageBitmap object whose bitmap has its origin-clean flag set to false.
The flag can be reset in certain situations; for example, when a CanvasRenderingContext2D is bound to a new canvas, the bitmap is cleared
and its flag reset.