WriteMySEO / Blog / A Stray Tag in <head> Ends It Before Your Canonical
SEO technology

A Stray Tag in <head> Ends It Before Your Canonical

The HTML parser closes <head> at the first element that doesn't belong there. Which tags trigger it, what you lose when they do, and how to audit it at scale.

Your rel=canonical is in the <head>. You can see it in view-source, right there between the title and the meta description. Google ignores it anyway, and the URL Inspection tool reports a different canonical than the one you declared.

The likely cause is not a Google bug. It is the HTML parsing algorithm doing exactly what the spec tells it to: closing the <head> element at the first token that isn't allowed inside it, and dumping everything after that point into <body>. Your canonical is in the body. So are your hreflang links, your meta robots tag, and your <base href>.

What actually ends the head

The HTML Standard defines an "in head" insertion mode with a short list of elements it accepts. Everything else hits the "anything else" clause, which pops the head off the stack, switches to "after head", and reprocesses the token — which in turn implies a <body> start tag.

Allowed in head (parsing continues)Ends the head immediately
base, link, meta, titleAny flow content: div, p, span, section
script, style, noscript, noframesimg, iframe, svg, math, form, table
template, comments, whitespaceAny non-whitespace text node

Two cases catch people out repeatedly.

Bare text. A stray character — a &nbsp; from a CMS editor, a templating artifact, a PHP warning printed before the next tag — is a character token, and non-whitespace character tokens are not allowed in head. One misplaced character closes it.

<noscript> with scripting enabled. noscript itself is legal in head, but the parser then enters "in head noscript" mode, which only accepts link, meta, style, noframes, and comments. The classic Google Tag Manager or Meta Pixel fallback — <noscript><iframe ...></iframe></noscript> — hits an iframe, pops out of the noscript, reprocesses in "in head", and closes the head. Those snippets are documented as body-placement for exactly this reason.

Note the asymmetry: stray end tags in head (</div>, </span>) are parse errors that get ignored, so they're harmless. It is start tags and text that do the damage.

Which of your tags stop counting

Once the head is closed, everything downstream is a body element. That matters differently per tag:

Why view-source and most crawlers miss it

View-source shows you bytes, not the parse tree. Your canonical is visually inside the head in the source text; it just isn't in the head in the DOM.

The bigger problem is tooling. Any crawler that extracts the head with a regex, a string split on </head>, or a lenient non-spec parser will report the canonical as present and correct. Chromium — which is what Googlebot renders with — follows the spec. So does parse5 in Node and html5lib in Python. lxml.html and similar permissive parsers do not reproduce this behavior reliably.

One caveat worth knowing: the noscript case depends on the parser's scripting flag. parse5 enables scripting by default; some parsers default to disabled, in which case the noscript content is parsed as markup and head termination can differ. Googlebot renders with scripting enabled, so match that.

How to check a single page in thirty seconds

Open DevTools on the rendered page and run:

const sels = ['link[rel="canonical"]', 'meta[name="robots"]',
              'link[rel="alternate"][hreflang]', 'base'];
sels.forEach(s => console.log(s,
  { inHead: !!document.head.querySelector(s),
    anywhere: !!document.querySelector(s) }));
console.log('last head child:', document.head.lastElementChild);
console.log('first body child:', document.body.firstElementChild);

Any selector where anywhere is true but inHead is false is an evicted tag. The firstElementChild of body tells you the culprit: if it's a div you expected to find in the head, you've found the terminating token. In the Elements panel the same thing is visible — the head ends abruptly and your meta tags appear as body children.

How to audit it across a whole site

At scale, parse with a spec-compliant parser and record the position of the break rather than just a boolean.

import html5lib, requests

doc = html5lib.parse(requests.get(url).text, namespaceHTMLElements=False)
head = doc.find('head')
head_tags = [el.tag for el in head]
canonical_in_head = any(
    el.tag == 'link' and el.get('rel') == 'canonical' for el in head
)

Three reporting fields make the output actionable: the number of elements in the parsed head, the tag name of the first body child, and a per-tag in_head flag for canonical, hreflang, robots, and base. A site with a template-level bug will show a near-identical head length across thousands of URLs — that's your signal that it is one partial, not scattered content errors.

Cross-check a sample against the rendered HTML in Search Console's URL Inspection tool. If Google reports a user-declared canonical of "none" while your source clearly contains one, the parse tree is where to look.

What to do about it

  1. Move the detectable tags first. Put base, link rel=canonical, hreflang links, meta robots, and charset at the very top of the head, before any third-party script, consent manager, or tag manager snippet. If the head breaks later, the tags that depend on head placement have already been parsed.
  2. Get tracking fallbacks out of the head. <noscript> blocks containing iframe or img belong immediately after the opening <body> tag, which is what the vendors specify.
  3. Audit server-side injection. CDN workers, A/B testing tools, and personalization layers that inject markup into the head are a frequent source, and they only appear in production — not in your local build.
  4. Add a parse-tree assertion to CI. One test that parses a representative template with a spec parser and asserts document.head contains the canonical is cheaper than discovering the problem through a canonical reassignment three weeks later.
  5. Fix your crawler config. If your audit tool reports canonicals by string matching, it will keep telling you the page is fine. Verify against rendered DOM for at least a sample of templates.
html parsingcanonicalrenderingindexing

WriteMySEO produces marketing content, not legal, medical, financial, or compliance advice. Figures cited reflect publicly reported industry data at time of writing and shift over time.

Get started

We write this well about your industry, every month.

AI-drafted, human-reviewed SEO content on a flat subscription. Blog posts, metadata, schema, and internal links, shipped on a monthly rhythm.

See plans

More from the blog