Stray end tag head как исправить
Перейти к содержимому

Stray end tag head как исправить

Проблема с валидностью кода

Хорошо, спасибо за советы. Попробуем.

Также есть такая ошибка: Stray end tag head. С чем она может быть связана?

  • Регистрация: 09.02.2013
  • Сообщений: 1,417
  • Репутация: 384
  • Webmoney BL: ?
  • Регистрация: 11.01.2015
  • Сообщений: 15
  • Репутация: 2
  • Регистрация: 09.02.2013
  • Сообщений: 1,417
  • Репутация: 384
  • Webmoney BL: ?
  • Регистрация: 11.01.2015
  • Сообщений: 15
  • Репутация: 2
  • Регистрация: 21.05.2014
  • Сообщений: 404
  • Репутация: 33
  • Webmoney BL: ?
  • Регистрация: 26.02.2014
  • Сообщений: 524
  • Репутация: 104
  • Webmoney BL: ?

Сообщение от smowin

  • Регистрация: 09.02.2013
  • Сообщений: 1,417
  • Репутация: 384
  • Webmoney BL: ?

Почему валидатор выдает ошибку?

Прохожу курс на htmlacademy, пытаюсь отправить проект на защиту, но не пропускает автоматический валидатор, причем выдает ошибки, которых нет.
P.S. наставники уже не помогают.

1. Пишет, что не указана кодировка, хотя она указана как на странице, так и в атоме, в котором пишу. Везде utf-8.
Так же выдает, что этот тег не закрыт. Пробовал написать его так , все равно пишет, что не закрыт и еще дополнительную ошибку на этот символ.
Еще пишет Bad element name “meta-charset=»utf-8″”: Code point “U+003D” is not allowed

2.Выдает ошибку в нескольких местах «Unmappable byte sequence: “81”. «. Что это означает понять не могу, первое слово вообще даже переводчик не берет.

3. Element “head” is missing a required instance of child element “title”. Так же не могу понять в чем ошибка, код выше.

4. Element “title” not allowed as child of element “meta-charset=»utf-8″” in this context.
Титульный элемент не допускается как дочерний к meta-charset.
Так же не понятно как исправить в связи с вопросами выше.

5. Stray end tag “head”. Переводчик перевел это как «шальное закрытие тега head. Это как понять? Код выше.

6. Start tag “body” seen but an element of the same type was already open. «Начальный тег body виден, но элемент того же типа уже открыт». Но у меня один на странице и он закрыт!

7. End tag for “body” seen, but there were unclosed elements. Говорит о незакрытых элементах, прошелся про каждому — нет незакрытых!

Как проверить HTML валидацию сайта — основные ошибки

Проверка валидности HTML кода сайта обязательно входит в мой технический аудит. Но не нужно переоценивать значимость ошибок валидации на SEO продвижение — она очень мала. По любой тематике в ТОП будут сайты с большим количеством таких ошибок и прекрасно себе живут.

НО! Отсутствие технических ошибок на сайте является фактором ранжирования, и поэтому пренебрегать такой возможностью не стоит. Лучше исправить, хуже точно не будет. Поисковики увидят ваши старания и дадут маленький плюсик в карму.

Как проверить сайт на валидность HTML кода

Проверяется валидация кода сайта с помощью онлайн сервиса W3C HTML Validator. Если есть ошибки, то сервис выдает вам список. Сейчас я разберу самые распространенные типы ошибок, которые я встречал на сайтах.

  • Error: Duplicate ID min_value_62222

Error Duplicate ID min_value_62222

И за этой ошибкой такое предупреждение.

  • Warning: The first occurrence of ID min_value_62222 was here

Warning The first occurrence of ID min_value_62222 was here

Это значит, что дублируется стилевой идентификатор ID, который по правилам валидности html должен быть уникальным. Вместо ID для повторяющихся объектов можно использовать CLASS.

Исправлять это желательно, но не очень критично. Если очень много таких ошибок, то лучше исправить.

Аналогично могут быть еще такие варианты:

  • Error: Duplicate ID placeWorkTimes
  • Error: Duplicate ID callbackCss-css
  • Error: Duplicate ID Capa_1

Следующее очень распространенное предупреждение.

  • Warning: The type attribute is unnecessary for JavaScript resources

Warning The type attribute is unnecessary for JavaScript resources

Это очень частая ошибка при проверке валидации сайта. По правилам HTML5 атрибут type для тега script не нужен, это устаревший элемент.

Аналогично такое предупреждение для стилей:

  • Warning: The type attribute for the style element is not needed and should be omitted

Warning The type attribute for the style element is not needed and should be omitted

Исправлять эти предупреждения желательно, но не критично. При большом количестве лучше исправить.

  • Warning: Consider avoiding viewport values that prevent users from resizing documents

Warning Consider avoiding viewport values that prevent users from resizing documents

Это предупреждение показывает, что нельзя увеличить размер страницы на мобильном или планшете. То есть пользователь захотел посмотреть поближе картинки или очень маленький текст и не может этого сделать.

Я считаю это предупреждение очень нежелательным, для пользователя неудобно, это минус к поведенческим. Устраняется удалением этих элементов — maximum-scale=1.0 и user-scalable=no.

  • Error: The itemprop attribute was specified, but the element is not a property of any item

Error The itemprop attribute was specified, but the element is not a property of any item

Это микроразметка, атрибут itemprop должен находиться внутри элемента с itemscope. Я считаю эту ошибку не критичной и можно оставлять как есть.

  • Warning: Documents should not use about:legacy-compat, except if generated by legacy systems that can’t output the standard doctype

Warning Documents should not use about legacy-compat, except if generated by legacy systems that can

Строка about:legacy-compat нужна только для html-генераторов. Здесь нужно просто сделать но ошибка совсем не критичная.

  • Error: Stray end tag source

Error Stray end tag source

Если посмотреть в коде самого сайта и найти этот элемент, видно, что одиночный тег <source> прописан как парный — это не верно.

одиночный тег source

Соответственно, нужно убрать из кода закрывающий тег </source>. Аналогично этой ошибке могут встречаться теги </meta> </input> </noscript>. Эту ошибку нужно исправлять.

  • Error: An img element must have an alt attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images

Error An img element must have an alt attribute, except under certain conditions For details, consult guidance on providing text alternatives for images

Все картинки должны иметь атрибут alt, я считаю эту ошибку критичной, ее нужно исправлять.

  • Error: Element ol not allowed as child of element ul in this context. (Suppressing further errors from this subtree.)

Error Element ol not allowed as child of element ul in this context Suppressing further errors from this subtree

Здесь не верно прописана вложенность тегов. В <ul> должны быть только <li>. В данном примере эти элементы вообще не нужны.

неправильная вложенность тегов

Аналогично могут быть еще такие ошибки:

  • Element h2 not allowed as child of element ul in this context.
  • Element a not allowed as child of element ul in this context.
  • Element noindex not allowed as child of element li in this context.
  • Element div not allowed as child of element ul in this context.

Это все нужно исправлять.

  • Error: Attribute http-equiv not allowed on element meta at this point

Error Attribute http-equiv not allowed on element meta at this point

Атрибут http-equiv не предназначен для элемента meta, нужно убрать его или заменить.

  • Error: Attribute n2-lightbox not allowed on element a at this point.
  • Error: Attribute asyncsrc not allowed on element script at this point.
  • Error: Attribute price not allowed on element option at this point.
  • Error: Attribute hashstring not allowed on element span at this point.

Здесь также нужно или убрать атрибуты n2-lightbox, asyncsrc, price, hashstring или заменить их на другие варианты.

  • Error: Bad start tag in img in head

Error Bad start tag in img in head

  • Error: Bad start tag in div in head

Error Bad start tag in div in head

Тегов img и div не должно быть в <head>. Эту ошибку нужно исправлять.

  • Error: CSS: Parse Error

Error CSS Parse Error

В данном случае здесь не должно быть точки с запятой после скобки в стилях.

не должно быть точки с запятой в стилях

Ну такая ошибка, мелочь, но не приятно) Смотрите сами, нужно убирать это или нет, на продвижение сайта никакой совершенно роли не окажет.

  • Warning: The charset attribute on the script element is obsolete

Warning The charset attribute on the script element is obsolete

В скриптах уже не нужно прописывать кодировку, это устаревший элемент. Предупреждение не критичное, на ваше усмотрение.

  • Error: Element script must not have attribute charset unless attribute src is also specified

Error Element script must not have attribute charset unless attribute src is also specified

В этой ошибке нужно убрать из скрипта атрибут charset=»uft-8″, так как он показывает кодировку вне скрипта. Я считаю, эту ошибку нужно исправлять.

  • Warning: Empty heading

Warning Empty heading

Здесь пустой заголовок h1. Нужно удалить теги <h1></h1> или поместить между ними заголовок. Ошибка критичная.

  • Error: End tag br

Error End tag br

Тег br одиночный, а сделан как будто закрывающий парный. Нужно убрать / из тега.

одиночный тег br

  • Error: Named character reference was not terminated by a semicolon. (Or & should have been escaped as &.)

Error Named character reference was not terminated by a semicolon

спецсимволы html

Это спецсимволы HTML, правильно нужно писать &copy; или &amp;copy. Лучше эту ошибку исправить.

  • Fatal Error: Cannot recover after last error. Any further errors will be ignored

Fatal Error Cannot recover after last error Any further errors will be ignored

Это серьезная ошибка:

код после html

После </html> ничего вообще не должно быть, так как это последний закрывающий тег страницы. Нужно удалять все, что после него или переносить выше.

  • Error: CSS: right: only 0 can be a unit. You must put a unit after your number

Error CSS right only 0 can be a unit You must put a unit after your number

Нужно значение в px написать:

значения в коде

Вот аналогичная ошибка:

  • Error: CSS: margin-top: only 0 can be a unit. You must put a unit after your number

Error CSS margin-top only 0 can be a unit You must put a unit after your number

  • Error: Unclosed element a

Error Unclosed element a

<a></a> — это парный тег, а здесь он не закрыт, соответственно, нужно закрыть. Ошибку исправлять.

  • Error: Start tag a seen but an element of the same type was already open

Где-то раньше уже был открыт тег <a> и не закрыт, откуда идет следующая ошибка.

  • Error: End tag a violates nesting rules

Здесь отсутствие закрывающего тега </a> нарушает правила вложенности, откуда идет уже фатальная ошибка.

  • Fatal Error: Cannot recover after last error. Any further errors will be ignored

Это частный случай, так конечно нужно смотреть индивидуально.

  • Warning: The bdi element is not supported in all browsers. Please be sure to test, and consider using a polyfill

Warning The bdi element is not supported in all browsers Please be sure to test, and consider using a polyfill

Элемент bdi не поддерживается во всех браузерах, лучше использовать стили CSS, если нужно изменить направления вывода текста. Это не критичное предупреждение.

  • Error: A document must not include both a meta element with an http-equiv attribute whose value is content-type, and a meta element with a charset attribute

Error A document must not include both a meta element with an http-equiv attribute whose value is content-type and a meta element with a charset attribute

Здесь 2 раза указана кодировка:

двойная кодировка

Нужно убрать <meta charset=»UTF-8″ /> в начале. Ошибку лучше исправить.

  • Error: Bad value callto:+7 (473) 263-22-06 for attribute href on element a: Illegal character in scheme data: space is not allowed

Error Bad value callto 7 495 263-22-06 for attribute href on element a Illegal character in scheme data space is not allowed

Здесь запрещены пробелы для атрибута href, нужно писать так — callto:74732632206. Ошибку лучше исправить, но не критично.

  • Error: CSS: max-width: Too many values or values are not recognized

Error CSS max-width Too many values or values are not recognized

И аналогичная ошибка:

  • Error: CSS: max-height: Too many values or values are not recognized

Error CSS max-height Too many values or values are not recognized

В данных случаях для max-width: и max-height: не поддерживается свойство auto. Должно быть конкретное значение в px, % и других единицах измерения для CSS. В целом, эти ошибки не критичные.

  • Error: The for attribute of the label element must refer to a non-hidden form control

Error The for attribute of the label element must refer to a non-hidden form control

Атрибут label должен относиться к фрагменту id с идентификатором «control-label». То есть нужно в код формы вставить кусок Тоже ошибка не критичная.

id элемент в коде

  • Error: Legacy encoding windows-1251 used. Documents must use UTF-8

Error Legacy encoding windows-1251 used Documents must use UTF-8

Кодировка windows-1251 уже устарела, сейчас везде используется utf-8. По хорошему нужно делать сайт изначально на utf-8, иначе он или отдельные страницы могут отображаться кракозябрами. Но это не критичная ошибка. Если у вас с сайтом все ок, то можно оставить, как есть.

Вот еще похожая ошибка:

  • Error: Bad value text/html; charset=windows-1251 for attribute content on element meta: charset= must be followed by utf-8

Error Bad value text html charset windows-1251 for attribute content on element meta charset must be followed by utf-8

Для атрибута content кодировка должна быть utf-8. Смотрите сами, хотите исправлять это или нет, не критично.

Заключение

После того, как сделана полная проверка, я составляю файл с грубыми ошибками и передаю его моим программистам или технической поддержке клиента. Кстати, почитайте интересную историю, как я искал себе программиста.

Итак, теперь вы знаете, как проверить валидацию сайта с помощью онлайн сервиса W3C HTML Validator, но как я сказал валидность кода далеко не самый важный фактор ранжирования, скорее всего после исправления ошибок вы не заметите существенной разницы в позициях или трафике сайта. Но я считаю, что все равно нужно привести сайт в порядок, и надеюсь, моя статья вам в этом помогла.

Сергей Моховиков

Здравствуйте! Я специалист по продвижению сайтов в поисковых системах Яндекс и Google. Веду свой блог и канал на YouTube, где рассказываю самые эффективные технологии раскрутки сайтов, которые применяю сам в своей работе.

HTML Validation: Fatal Error

This HTML document is purposely invalid demonstrating the incorrect use of <noscript><img></noscript> in the <head></head> section. Validate this Document and View Source for more information.

Have you seen this error while validating your HTML documents? If so, you’ll want to correct this as soon as possible, it may be breaking the <head></head> section of your documents.

  1. Error: Bad start tag in <img> in <head> .
  2. Error: Stray end tag <noscript> .
  3. Error: Stray end tag <head> .
  4. Error: Start tag <body> seen but an element of the same type was already open.
  5. Fatal Error: Cannot recover after last error. Any further errors will be ignored.

The above shows the first error which is the <img> in the <head> . At the close of the <img> the validator has terminated the <head> and marks the </noscript> and </head> as stray end tags. Any other code that sits below the <img> error in the <head></head> is marked as an error due to the early termination of the <head> element.

Facebook Pixel Code Breaks <head></head>

If you are using the Facebook Pixel Code and have followed their instructions for inserting that code, you have this error in your <head></head> section. If you have a class on your <body > element, you’ll see the Fatal Error label. We haven’t figured out why, when the class attribute is added to the <body> , that it invokes the Fatal Error Label from the validator.

How to Fix this Fatal Error

Move this part of the Facebook Pixel Code <noscript><img></noscript> to the <body> , you can place it right after the opening <body> element. This also applies to any other invalid use of <noscript> in the <head></head> element e.g. <noscript><iframe></iframe></noscript> .

What is the <noscript> Element?

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.
W3C Recommendation: Scripting > 4.12.2 The noscript element

When used inside the <head> element the <noscript> must contain ONLY <link> , <style> , and <meta> elements. If the <noscript> inside the <head> contains anything other than those three elements, a validation error will occur and the <head> may be closed prematurely and everything after the </noscript> element may be ignored and moved to the <body> during the building of the DOM.

John Mueller from Google states that it breaks everything within the <head></head> .

Google Confirms Breaking <head> Section Can Make hreflang Unrecognizable

Barry Schwartz from Search Engine Roundtable: “Google’s John Mueller said in a Google Hangout on Google+ last Friday that sometimes when href lang doesn’t get picked up, it might be that the header section of your HTML is broken. When that happens, Google can’t recognize that there is href lang code in there and doesn’t show any href lang errors to you because it is not apparent to Google that the code exists there.”

John Mueller from Google: “So it might just be that we don’t recognize the hreflang markup at all on those pages.

For example, what might happen is we can crawl and index those pages, but when we render those pages, something in the <head> section of the pages is added early on, and that kind of breaks everything within the <head></head> , which includes the hreflang markup.

So that might theoretically be happening. And if we can’t find the hreflang markup at all, we won’t flag it as an error, because we think there is nothing wrong with a page that doesn’t have hreflang .

So that might be something worth double checking. So what you can do there is open the page in a browser and use Inspect Element to see what the rendered view of the page actually looks like. And then double check to make sure that within the head section there is actually nothing like non-meta tag type that’s actually listed there.”

John Mueller from Google: 2018-03-28 “A somewhat niche technical issue I’ve seen recently is that some kinds of scripts (including some from Google) inject non-head HTML tags into the top of the head on a page. For us, this implicitly closes the head, and brings all of the meta-tags into the body of the page. For hreflang , that often results in those annotations being dropped completely. If you use hreflang , I’d double-check the rendered source with the Rich Results testing tool (it’s the only one that currently shows the rendered source), and check that there are no iframe’s or div’s above the hreflang annotations.”
Reddit > r/TechSEO

References Regarding <noscript> in <head></head> Section

“This means that the URL in question contains a <noscript> tag in the <head> , which includes an image reference. The <noscript> tag defines an alternate content for users that have disabled scripts in their browser or have a browser that doesn’t support script.”

“Whilst it can be used in both the <head> and the <body> , when used inside the <head> , it must contain only <link> , <style> , and <meta> elements. As such, including an <img> tag is invalid.”

“This can be problematic for search engine crawlers that do not render JavaScript (i.e. most crawlers, most of the time), as the presence of the <img> tag breaks the <head> , which may cause important tags (e.g. meta robots) to be missed.”

“Facebook Pixel Code consists of two parts: <script> and <noscript> . The latter is designed to track the visitors when JavaScript disabled in their browsers. If you paste the entire Facebook Pixel Code to Custom HTML tag in Google Tag Manager, the <noscript> part just won’t work. If you still care about a tiny fraction of additional visitors and want to track them, you’ll need to create a separate tag for that. That’s where the Custom Image tag comes in handy.”

Quotes from Google Regarding Validation

Why does validation matter? There are different perspectives on validation – at Google there are different approaches and priorities too – but the Webmaster Team considers validation a baseline quality attribute.
Validation: Measuring and Tracking Code Quality

Consider validating your code. If your code passes validation, you’ve eliminated one potential issue in browser compatibility. With validated code, you won’t need to rely on each browsers’ error handling technique. There’s a greater chance that your code will function across different browsers, and it’s easier to debug potential problems.
Workin’ It on all Browsers

Use valid HTML. We also detect the price that you’re displaying based on the structure of your landing page. Using valid HTML helps ensure that we detect the correct price. Keep in mind that even with valid HTML, you must still use microdata to enable automatic item updates. Use the W3C validation service to check your HTML
Tips to Help Your Products Stay Approved

Write good, clean HTML. While your site may appear correctly in some browsers even if your HTML is not valid, there’s no guarantee that it will appear correctly in all browsers – or in all future browsers. The best way to make sure that your page looks the same in all browsers is to write your page using valid HTML and CSS, and then test it in as many browsers as possible. Clean, valid HTML is a good insurance policy, and using CSS separates presentation from content, and can help pages render and load faster.
Browser Compatibility

Following the General Guidelines below will help Google find, index, and rank your site. > Help visitors use your pages. > Use valid HTML.
Webmaster Guidelines

Why did my crawl rate drop? In general, your Google crawl rate should be relatively stable over the time span of a week or two; if you see a sudden drop, here are a few possible reasons:

Broken HTML or unsupported content on your pages: If Googlebot can’t parse the content of the page it won’t be able to crawl them.
Crawl Stats Report

Dear JavaScript frameworks and plugins, if you could stop putting invalid tags in the HTML head, like IMG and DIV, that would be great.
Gary Illyes from Google

HTML and Debugging

“HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). And HTML’s element syntax is arguably a lot easier to understand than a «real programming language» like Rust, JavaScript, or Python. The way that browsers parse HTML is a lot more permissive than how programming languages are run, which is both a good and a bad thing.”

“HTML itself doesn’t suffer from syntax errors because browsers parse it permissively, meaning that the page still displays even if there are syntax errors. Browsers have built-in rules to state how to interpret incorrectly written markup, so you’ll get something running, even if it is not what you expected. This, of course, can still be a problem!”
Debugging HTML

HTML Validation – Why Validate?

“The core reason to run your HTML documents through a conformance checker is simple: To catch unintended mistakes – mistakes you might have otherwise missed – so that you can fix them. Beyond that, some document-conformance requirements (validity rules) in the HTML spec are there to help you and the users of your documents avoid certain kinds of potential problems.”

“There are some markup cases defined as errors because they are potential problems for accessibility, usability, interoperability, security, or maintainability – or because they can result in poor performance, or that might cause your scripts to fail in ways that are hard to troubleshoot.”

“Along with those, some markup cases are defined as errors because they can cause you to run into potential problems in HTML parsing and error-handling behavior – so that, say, you’d end up with some unintuitive, unexpected result in the DOM. Validating your documents alerts you to those potential problems.”

Need Help with HTML Validation?

I am very intimate with the HTML errors most websites generate and have validated over a million documents during my tenure (since 1995). I am available to assist Developers with validating their HTML documents at a minimal fee. Most validation routines can be handled in under an hour. Others may require multiple sessions. Either way, this is NOT rocket science and most Developers get IT after the first crash course consultation/validation routine at which time my services are no longer required. Contact me for more information.

The reason for any “Cannot recover after last error” message you get from the validator is that in the backend we run the HTML parser in truly streaming mode. That’s for performance reasons, among other reasons.
W3C Mailing Lists

Published: Mon, Jun 25, 2018
Updated: Fri, Mar 22, 2019

Facebook Pixel Code

The instructions provided by Facebook for inserting their Pixel Code generates an Error or Fatal Error in the <head></head> section of your HTML5 documents.

Facebook Pixel Code Instructions Validation Visual

© XSymmetry LLC • Operating Remotely from Southern California, USA

All rights reserved. All trademarks and servicemarks are the properties of their respective owners.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *