HTML5 Parser

  • Revision slug: Web/Guide/HTML/HTML5/HTML5_Parser
  • Revision title: HTML5 Parser
  • Revision id: 391589
  • Created:
  • Creator: Sheppy
  • Is current revision? No
  • Comment Fix a character that was supposed to be an ASCII single quote but that had gotten "smartened" along the way; 1 words added, 1 words removedMoved From HTML/HTML5/HTML5_Parser to Web/Guide/HTML/HTML5/HTML5_Parser

Revision Content

{{ gecko_minversion_header("2") }}

Gecko 2 introduces a new parser, based on HTML5. The HTML parser is one of the most complicated and sensitive pieces of a browser. It controls how your HTML source code is turned into web pages and, as such, changes to it are rare. The new parser is faster, complies with the HTML5 standard, and enables a lot of new functionality as well.

The new parser introduces these major improvements:

  • You can now use SVG and MathML inline in HTML5 pages, without XML namespace syntax.
  • Parsing is now done in a separate thread from Firefox’s main UI thread, improving overall browser responsiveness.
  • Calls to innerHTML are a lot faster.
  • Dozens of long-standing parser related bugs are now fixed.

The HTML5 specification provides a more detailed description than previous HTML standards of how to turn a stream of bytes into a DOM tree. This will result in more consistent behavior across browser implementations. In other words, in supporting HTML5, Gecko, WebKit, and Internet Explorer (IE) will behave more consistently with each other.

Changed parser behaviors

Some changes to the way that the Gecko 2 parser behaves, as compared to earlier versions of Gecko, may affect web developers, depending on how you've written your code in the past and what browsers you've tested it on.

Tokenization of left angle-bracket within a tag

Given the string <foo<bar>, the new parser reads it as one tag named foo<bar. This behavior is consistent with IE and Opera, and is different from Gecko 1.x and WebKit, which read it as two tags, foo and bar. If you previously tested your code in IE and Opera, then you probably don't have any tags like this. If you tested your site only with Gecko 1.x or WebKit (for example, Firefox-only intranets or WebKit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with Gecko 2.

Calling document.write() during parsing

Prior to HTML5, Gecko and WebKit allowed calls to document.write() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call to document.open(), replacing the document. In HTML5, document.write() can only be called from a script that is created by a {{ HTMLElement("script") }} tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write() in any other context either are ignored or replace the document.

Some contexts from which you should not call document.write() include:

If you use the same mechanism for loading script libraries for all browsers including IE, then your code probably will not be affected by this change. Scripts that serve racy code to Firefox, perhaps while serving safe code to IE, will see a difference due to this change. Firefox writes a warning to the JavaScript console when it ignores a call to document.write().

Lack of Reparsing

Prior to HTML5, parsers reparsed the document if they hit the end of the file within certain elements or within comments. For example, if the document lacked a </title> closing tag, the parser would reparse to look for the first '<' in the document, or if a comment was not closed, it would look for the first '>'. This behavior created a security vulnerability. If an attacker could force a premature end-of-file, the parser might change which parts of the document it considered to be executable scripts. In addition, supporting reparsing led to unnecessarily complex parsing code.

With HTML5, parsers no longer reparse documents. This change has the following consequences for web developers:

  • If you omit the closing tag for <title>, <style>, <textarea>, or <xmp>, the page will fail to be parsed. IE already fails to parse documents with a missing </title> tag, so if you test with IE, you probably don't have that problem.
  • If you forget to close a comment, the page will most likely fail to be parsed. However, unclosed comments often already break in existing browsers for one reason or another, so it's unlikely that you have this issue in sites that are tested in multiple browsers.
  • In an inline script, in order to use the literal strings <script</script>, and <!--, you should prevent them from being parsed literally by expressing them as \u003cscript,\u003c/script>, and \u003c!--. The older practice of escaping the string </script> by surrounding it with comment markers, while supported by HTML5, is problematic in cases where the closing comment marker is omitted (see preceding point). You can avoid such problems by using the character code for the initial '<' instead. (It is valid to use an escape character, e.g., <\/script>, but this strategy does not work for <script and <!--, because \s and \! are not valid JavaScript escapes; the character code strategy is more general-purpose.)

Inline SVG and MathML support

As a completely new parsing feature, HTML5 introduced support for inline SVG and MathML in text/html. This means that you can now use SVG and MathML inline in text/html similarly to what has previously been possible in application/xhtml+xml.

  • <svg></svg> is assigned to the SVG namespace in the DOM.
  • <math></math> is assigned to the MathML namespace in the DOM.
  • foreignObject and annotation-xml (an various less important elements) establish a nested HTML scope, so you can nest SVG, MathML and HTML as you’d expect to be able to nest them.
  • The parser case-corrects markup so <SVG VIEWBOX='0 0 10 10'> works in HTML source.
  • The DOM methods and CSS selectors behave case-sensitively, so you need to write your DOM calls and CSS selectors using the canonical case, which is camelCase for various parts of SVG such as viewBox.
  • The syntax <foo/> opens and immediately closes the foo element if it is a MathML or SVG element (i.e. not an HTML element).
  • Attributes are tokenized the same way they are tokenized in HTML, so you can omit quotes in the same situations where you can omit quotes in HTML (i.e. when the attribute value is not the empty string and does not contain whitespace, ", ', `, <, =, or >).
  • Warning: the two above features do not combine well due to the reuse of legacy-compatible HTML tokenization. If you omit quotes on the last attribute value, you must have a space before the closing slash. <circle fill=green /> is OK but <circle fill=red/> is not.
  • Attributes starting with xmlns have absolutely no effect on what namespace elements or attributes end up in, so you don’t need to use attributes starting with xmlns.
  • Attributes in the XLink namespace must use the prefix xlink (e.g. xlink:href).
  • Element names must not have prefixes or colons in them.
  • The content of SVG script elements is tokenized like they are tokenized in XML—not like the content of HTML script elements is tokenized.
  • When an SVG or MathML element is open <![CDATA[]]> sections work the way they do in XML. You can use this to hide text content from older browsers that don’t support SVG or MathML in text/html.
  • The MathML named characters are available for use in named character references everywhere in the document (also in HTML content).
  • To deal with legacy pages where authors have pasted partial SVG fragments into HTML (who knows why) or used a <math> tag for non-MathML purposes, attempts to nest various common HTML elements as children of SVG elements (without foreignObject) will immediately break out of SVG or MathML context. This may make some typos have surprising effects.

Performance improvement with speculative parsing

Unrelated to the requirements of HTML5 specification, the Gecko 2 parser uses speculative parsing, in which it continues parsing a document while scripts are being downloaded and executed. This results in improved performance compared to older parsers, because most of the time, Gecko can complete these tasks in parallel.

To best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call document.write(), you write a balanced sub-tree within that chunk of script. A balanced sub-tree is HTML code in which any elements that are opened are also closed, so that after the script, the elements left open are the same ones that were open before the script. The open and closing tags do not need to be written by the same document.write() call, as long as they are within the same <script> tag.

Please note that you shouldn't use end tags for void elements that don't have end tags: {{ HTMLElement('area') }}, {{ HTMLElement('base') }}, {{ HTMLElement('br') }}, {{ HTMLElement('col') }}, {{ HTMLElement('command') }}, {{ HTMLElement('embed') }}, {{ HTMLElement('hr') }}, {{ HTMLElement('img') }}, {{ HTMLElement('input') }}, {{ HTMLElement('keygen') }}, {{ HTMLElement('link') }}, {{ HTMLElement('meta') }}, {{ HTMLElement('param') }}, {{ HTMLElement('source') }} and {{ HTMLElement('wbr') }}. (There are also some element whose end tags can be omitted in some cases, such as {{ HTMLElement('p') }} in the example below, but it's simpler to always use end tags for those elements than to make sure that the end tags are only omitted when they aren't necessary.)

For example, the following code writes a balanced sub-tree:

<script>
  document.write("<div>");
  document.write("<p>Some content goes here.</p>");
  document.write("</div>");
</script>
<!-- Non-script HTML goes here. -->

In contrast, the following code contains two scripts with unbalanced sub-trees, which causes speculative parsing to fail and therefore the time to parse the document is longer.

<script>document.write("<div>");</script>
<p>Some content goes here.</p>
<script>document.write("</div>");</script>

For more information, see Optimizing your pages for speculative parsing.

 

{{ languages ( { "es": "es/HTML/HTML5/HTML5_Parser" } ) }}

Revision Source

<p>{{ gecko_minversion_header("2") }}</p>
<p>Gecko 2 introduces a new parser, based on HTML5. The HTML parser is one of the most complicated and sensitive pieces of a browser. It controls how your HTML source code is turned into web pages and, as such, changes to it are rare. The new parser is faster, complies with the HTML5 standard, and enables a lot of new functionality as well.</p>
<p>The new parser introduces these major improvements:</p>
<ul> <li>You can now use SVG and MathML inline in HTML5 pages, without XML namespace syntax.</li> <li>Parsing is now done in a separate thread from Firefox’s main UI thread, improving overall browser responsiveness.</li> <li>Calls to <code>innerHTML</code> are a lot faster.</li> <li><a class=" external" href="http://tinyurl.com/html-parser-bugs" title="https://bugzilla.mozilla.org/buglist.cgi?status_whiteboard_type=substring&amp;status_whiteboard=[fixed%20by%20the%20HTML5%20parser]&amp;resolution=FIXED">Dozens of long-standing parser related bugs</a> are now fixed.</li>
</ul>
<p>The <a class=" external" href="http://www.w3.org/TR/html5/" title="http://www.w3.org/TR/html5/">HTML5 specification</a> provides a more detailed description than previous HTML standards of how to turn a stream of bytes into a DOM tree. This will result in more consistent behavior across browser implementations. In other words, in supporting HTML5, Gecko, WebKit, and Internet Explorer (IE) will behave more consistently with each other.</p>
<h2 id="Changed_parser_behaviors">Changed parser behaviors</h2>
<p>Some changes to the way that the Gecko 2 parser behaves, as compared to earlier versions of Gecko, may affect web developers, depending on how you've written your code in the past and what browsers you've tested it on.</p>
<h3 id="Tokenization_of_left_angle-bracket_within_a_tag">Tokenization of left angle-bracket within a tag</h3>
<p>Given the string <code>&lt;foo&lt;bar&gt;</code>, the new parser reads it as one tag named <code>foo&lt;bar</code>. This behavior is consistent with IE and Opera, and is different from Gecko 1.x and WebKit, which read it as two tags, <code>foo</code> and <code>bar</code>. If you previously tested your code in IE and Opera, then you probably don't have any tags like this. If you tested your site only with Gecko 1.x or WebKit (for example, Firefox-only intranets or WebKit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with Gecko 2.</p>
<h3 id="Calling_document.write()_during_parsing">Calling document.write() during parsing</h3>
<p>Prior to HTML5, Gecko and WebKit allowed calls to <a href="/en/DOM/document.write" title="en/DOM/document.write"><code>document.write()</code></a> <em>during parsing</em> to insert content into the source stream. This behavior was inherently <a class=" external" href="http://en.wikipedia.org/wiki/Race_condition" title="http://en.wikipedia.org/wiki/Race_condition">racy</a>, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call to <a href="/en/DOM/document.open" title="en/DOM/document.open"><code>document.open()</code></a>, replacing the document. In HTML5, <code>document.write()</code> can only be called from a script that is created by a {{ HTMLElement("script") }} tag that does not have the <code><a href="/En/HTML/Element/Script#attr_async" title="En/HTML/Element/Script#attr async">async</a></code> or <code><a href="/En/HTML/Element/Script#attr_defer" title="En/HTML/Element/Script#attr defer">defer</a></code> attributes set. With the HTML5 parser, calls to <code>document.write()</code> in any other context either are ignored or replace the document.</p>
<p>Some contexts from which you should <em>not</em> call <code>document.write()</code> include:</p>
<ul> <li>scripts created using <a href="/en/DOM/document.createElement" title="en/DOM/document.createElement">document.createElement()</a></li> <li>event handlers</li> <li><a href="/en/DOM/window.setTimeout" title="en/DOM/window.setTimeout">setTimeout()</a></li> <li><a href="/en/DOM/window.setInterval" title="en/DOM/window.setInterval">setInterval()</a></li> <li><code>&lt;script async src="..."&gt;</code></li> <li><code>&lt;script defer src="..."&gt;</code></li>
</ul>
<p>If you use the same mechanism for loading script libraries for all browsers including IE, then your code probably will not be affected by this change. Scripts that serve racy code to Firefox, perhaps while serving safe code to IE, will see a difference due to this change. Firefox writes a warning to the JavaScript console when it ignores a call to <code>document.write()</code>.</p>
<h3 id="Lack_of_Reparsing">Lack of Reparsing</h3>
<p>Prior to HTML5, parsers reparsed the document if they hit the end of the file within certain elements or within comments. For example, if the document lacked a <code>&lt;/title&gt;</code> closing tag, the parser would reparse to look for the first '&lt;' in the document, or if a comment was not closed, it would look for the first '&gt;'. This behavior created a security vulnerability. If an attacker could force a premature end-of-file, the parser might change which parts of the document it considered to be executable scripts. In addition, supporting reparsing led to unnecessarily complex parsing code.</p>
<p>With HTML5, parsers no longer reparse documents. This change has the following consequences for web developers:</p>
<ul> <li>If you omit the closing tag for &lt;title&gt;, &lt;style&gt;, &lt;textarea&gt;, or &lt;xmp&gt;, the page <em>will</em> fail to be parsed. IE already fails to parse documents with a missing &lt;/title&gt; tag, so if you test with IE, you probably don't have that problem.</li> <li>If you forget to close a comment, the page will most likely fail to be parsed. However, unclosed comments often already break in existing browsers for one reason or another, so it's unlikely that you have this issue in sites that are tested in multiple browsers.</li> <li>In an inline script, in order to use the literal strings <code>&lt;script</code>,  <code>&lt;/script&gt;,</code> and <code>&lt;!--</code>, you should prevent them from being parsed literally by expressing them as <code>\u003cscript</code><code>,</code><code>\u003c/script&gt;</code>, and <code>\u003c!--</code>. The older practice of escaping the string <code>&lt;/script&gt;</code> by surrounding it with comment markers, while supported by HTML5, is problematic in cases where the closing comment marker is omitted (see preceding point). You can avoid such problems by using the character code for the initial '&lt;' instead. (It is valid to use an escape character, e.g., <code>&lt;\/script&gt;</code>, but this strategy does not work for <code>&lt;script</code> and <code>&lt;!--</code>, because <code>\s</code> and <code>\!</code> are not valid JavaScript escapes; the character code strategy is more general-purpose.)</li>
</ul>
<h3 id="Inline_SVG_and_MathML support">Inline SVG and MathML support</h3>
<p>As a completely new parsing feature, HTML5 introduced support for inline SVG and MathML in <code>text/html</code>. This means that you can now use SVG and MathML inline in <code>text/html</code> similarly to what has previously been possible in <code>application/xhtml+xml</code>.</p>
<ul> <li><code>&lt;svg&gt;</code>…<code>&lt;/svg&gt;</code> is assigned to the SVG namespace in the DOM.</li> <li><code>&lt;math&gt;</code>…<code>&lt;/math&gt;</code> is assigned to the MathML namespace in the DOM.</li> <li><code>foreignObject</code> and <code>annotation-xml</code> (an various less important elements) establish a nested HTML scope, so you can nest SVG, MathML and HTML as you’d expect to be able to nest them.</li> <li>The parser case-corrects markup so <code>&lt;SVG VIEWBOX='0 0 10 10'&gt;</code> works in HTML source.</li> <li>The DOM methods and CSS selectors behave case-sensitively, so you need to write your DOM calls and CSS selectors using the canonical case, which is camelCase for various parts of SVG such as <code>viewBox</code>.</li> <li>The syntax <code>&lt;foo/&gt;</code> opens and immediately closes the <code>foo</code> element if it is a MathML or SVG element (i.e. not an HTML element).</li> <li>Attributes are tokenized the same way they are tokenized in HTML, so you can omit quotes in the same situations where you can omit quotes in HTML (i.e. when the attribute value is not the empty string and does not contain whitespace, <code>"</code>, <code>'</code>, <code>`</code>, <code>&lt;</code>, <code>=</code>, or <code>&gt;</code>).</li> <li><strong>Warning:</strong> the two above features do not combine well due to the reuse of legacy-compatible HTML tokenization. If you omit quotes on the last attribute value, you must have a space before the closing slash. <code>&lt;circle fill=green /&gt;</code> is OK but <code>&lt;circle fill=red/&gt;</code> is not.</li> <li>Attributes starting with <code>xmlns</code> have <em>absolutely no effect</em> on what namespace elements or attributes end up in, so you don’t need to use attributes starting with <code>xmlns</code>.</li> <li>Attributes in the XLink namespace must use the prefix <code>xlink</code> (e.g. <code>xlink:href</code>).</li> <li>Element names must not have prefixes or colons in them.</li> <li>The content of SVG <code>script</code> elements is tokenized like they are tokenized in XML—not like the content of HTML <code>script</code> elements is tokenized.</li> <li>When an SVG or MathML element is open <code>&lt;![CDATA[</code>…<code>]]&gt;</code> sections work the way they do in XML. You can use this to hide text content from older browsers that don’t support SVG or MathML in <code>text/html</code>.</li> <li>The MathML named characters are available for use in named character references everywhere in the document (also in HTML content).</li> <li>To deal with legacy pages where authors have pasted partial SVG fragments into HTML (who knows why) or used a <code>&lt;math&gt;</code> tag for non-MathML purposes, attempts to nest various common HTML elements as children of SVG elements (without <code>foreignObject</code>) will immediately break out of SVG or MathML context. This may make some typos have surprising effects.</li>
</ul>
<h2 id="Performance_improvement_with_speculative_parsing">Performance improvement with speculative parsing</h2>
<p>Unrelated to the requirements of HTML5 specification, the Gecko 2 parser uses <em>speculative parsing</em>, in which it continues parsing a document while scripts are being downloaded and executed. This results in improved performance compared to older parsers, because most of the time, Gecko can complete these tasks in parallel.</p>
<p>To best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call <a href="/en/DOM/document.write" title="en/DOM/document.write">document.write()</a>, you write a <em>balanced sub-tree</em> within that chunk of script. A balanced sub-tree is HTML code in which any elements that are opened are also closed, so that after the script, the elements left open are the same ones that were open before the script. The open and closing tags do not need to be written by the same <code>document.write()</code> call, as long as they are within the same <code>&lt;script&gt;</code> tag.</p>
<p>Please note that you shouldn't use end tags for void elements that don't have end tags: {{ HTMLElement('area') }}, {{ HTMLElement('base') }}, {{ HTMLElement('br') }}, {{ HTMLElement('col') }}, {{ HTMLElement('command') }}, {{ HTMLElement('embed') }}, {{ HTMLElement('hr') }}, {{ HTMLElement('img') }}, {{ HTMLElement('input') }}, {{ HTMLElement('keygen') }}, {{ HTMLElement('link') }}, {{ HTMLElement('meta') }}, {{ HTMLElement('param') }}, {{ HTMLElement('source') }} and {{ HTMLElement('wbr') }}. (There are also some element whose end tags can be omitted in some cases, such as {{ HTMLElement('p') }} in the example below, but it's simpler to always use end tags for those elements than to make sure that the end tags are only omitted when they aren't necessary.)</p>
<p>For example, the following code writes a balanced sub-tree:</p>
<pre>&lt;script&gt;
  document.write("&lt;div&gt;");
  document.write("&lt;p&gt;Some content goes here.&lt;/p&gt;");
  document.write("&lt;/div&gt;");
&lt;/script&gt;
&lt;!-- Non-script HTML goes here. --&gt;
</pre>
<p>In contrast, the following code contains two scripts with unbalanced sub-trees, which causes speculative parsing to fail and therefore the time to parse the document is longer.</p>
<pre>&lt;script&gt;document.write("&lt;div&gt;");&lt;/script&gt;
&lt;p&gt;Some content goes here.&lt;/p&gt;
&lt;script&gt;document.write("&lt;/div&gt;");&lt;/script&gt;
</pre>
<p>For more information, see <a href="/en/HTML/HTML5/Optimizing_Your_Pages_for_Speculative_Parsing" title="en/Optimizing Your Pages for Speculative Parsing">Optimizing your pages for speculative parsing</a>.</p>
<p> </p>
<p>{{ languages ( { "es": "es/HTML/HTML5/HTML5_Parser" } ) }}</p>
Revert to this revision