Статьи

Спецификации W3C и WHATWG HTML5 — документированные различия

Автор Аурелио Де Роса для Telerik Blog.

w3c_whatwg_header

Несколько недель назад HTML5 стал официальной Рекомендацией W3C. Я воспользовался этим событием, чтобы обсудить 5 интересных, но уже устаревших функций в SitePoint. Проблема в том, что спецификации W3C — это только одна сторона одной медали. Начиная с этой версии HTML, разработчики и поставщики браузеров могут выбирать между двумя вариантами одного и того же языка разметки: спецификациями, разработанными W3C, и спецификациями, разработанными WHATWG.

По большей части эти спецификации одинаковы или очень похожи, но с годами появляются все новые и новые различия. Должны ли вы заботиться о них? В большинстве случаев вам не следует этого делать, потому что либо они мало что изменят для вас и ваших проектов, либо поставщики браузеров будут поддерживать оба стандарта. Однако в краткосрочной перспективе для вас могут быть важны другие различия, так как они влияют на реализацию данной функции. У каждого поставщика браузеров есть свои взгляды на то, какой спецификации следовать Например, Дэвид Барон из Mozilla недавно заявил :

Когда спецификации HTML W3C и WHATWG различаются, мы склонны следовать спецификации WHATWG.

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

«HTML5» против «HTML Living Standard»

Давайте начнем эту дискуссию о различиях с простой темы: название стандарта. Версия WHATWG спецификации была переименована в начале 2011 года в «HTML» опуская «5» в конце имени. Затем он был переименован в «HTML Living Standard», чтобы указать, что он будет в постоянной разработке и больше не будет ссылаться с использованием номера версии.

Напротив, спецификации W3C по- прежнему используют номера версий, и, как я уже упоминал во введении, последняя стабильная версия — 5, то есть HTML5. В результате этого шага консорциум сейчас активно разрабатывает новую версию стандарта, известную как HTML5.1. В HTML5.1 обсуждаются некоторые элементы и атрибуты, которые не нашли своего места в HTML5, такие как dialogэлемент и новые inputтипы monthи week.

мнение

Я думаю, что современный мир действительно отличается от начала 2000-х, потому что технологии развиваются в еще более безумном темпе, особенно в Интернете. Таким образом, звучит разумно иметь чувство непрерывности, отбрасывая любой номер версии. Однако не каждый браузер автоматически обновляется или выпускается в одном и том же темпе (обычно используется термин « вечнозеленый браузер» ), поэтому все же имеет смысл сопоставить набор функций одной или нескольким версиям браузера.

Мое мнение таково, что пока каждый браузер не примет эту политику быстрых выпусков и автообновлений, наличие версии, на которую могут ссылаться разработчики, позволяет лучше планировать. Не потому, что вам следует разрабатывать веб-сайты, которые определяют версию браузера для использования определенной функции (для этого вам действительно следует использовать подход обнаружения функции), а потому, что с определенной версией браузера мы можем получить статистику ее использования. Используя такую ​​статистику, вы можете спланировать, подходит ли вам время для использования определенной функции в вашем проекте. Да, полифилы и прокладки могут помочь, но вам нужно учитывать, какой вес вы готовы добавить на свой сайт?

mainэлемент

The main element is one the latest additions to the specifications and it has different meaning depending on the specifications. The W3C specifications describe it as the main content of the page – the content that describes the main topic of a page or is the central functionality of an application. The specifications also assert that a document must not include more than one main element and that the main element has to be mapped to the ARIA role="main" or equivalent in accessibility APIs.

A simple example of use based on this specification is shown below:

<body>
   <header>
      <h1>Main title</h1>
   </header>
   <main>
      <article>
         <h1>Main title</h1>
         <p>This is the content of this section</p>
         <footer>
            The author of this content is Aurelio De Rosa
         </footer>
      </article>
   </main>
   <footer>
      <small>Copyright © Aurelio De Rosa 2014</small>
   </footer>
</body>

The WHATWG specifications don’t assign any semantic value to the main element and describe it as a container for the dominant contents of another element. If you adhere to the WHATWG specifications you don’t have a limit in the number of times you can use the main element. Therefore if you have multiple article elements on a page you might markup the content of each article with the main element.

An example of use based on the WHATWG specifications could be:

<body>
   <header>
      <h1>Main title</h1>
   </header>
   <main>
      <article>
         <h1>Main title</h1>
         <main>
            <p>This is the content of this section</p>
         </main>
         <footer>
            The author of this content is Aurelio De Rosa
         </footer>
      </article>
   </main>
   <footer>
      <small>Copyright © Aurelio De Rosa 2014</small>
   </footer>
</body>

Note how in the code above I used the main element twice.

Opinion

In regard to the main element, I’m with the W3C because I doubt that people have the need for multiple main areas in a document. In addition, I recall that Steve Faulkner (the editor of the W3C specifications) has urged Ian Hickson (the editor of the WHATWG specifications) multiple times on the WHATWG mailing list to show data that proved the need for multiple main areas. The conclusion was that in all the occasions the WHATWG editor failed in providing such data.

The hgroup element

The hgroup element is used to group a set of one or more h1h6 elements, useful to group a section title and an accompanying subtitle.

This element was introduced to easily create subtitles and address an important problem in the document outline algorithm. In fact, when grouping multiple heading elements in an hgroup, the outline algorithm was supposed to mask all but the highest level heading in the group from the resulting document outline.

An example of its use, taken from my article 5 Obsolete Features in HTML5, is shown below:

<article>
   <hgroup>
      <h1>5 deprecated features of HTML5</h1>
      <h2>Sometimes specifications are changed
      and you need to refactor your code</h2>
   </hgroup>
   <p>In this article we'll discuss...</p>
</article>

In April 2013 this element was removed from the W3C’s specification due to lack of implementations, lack of use cases, and promoted markup anti-pattern. On the contrary, the WHATWG spec still includes hgroup.

Opinion

As stated in the cited article, I’ve been a huge fan of this element but I dropped its use. The first reason for my choice is that I’m mostly a follower of the W3C specifications. The second reason is that I noticed this lack of interest and implementation among browsers.

Web Notifications API

The Web Notifications API is defined as an API for end-user notifications. A notification allows alerting the user outside the context of a web page of an occurrence, such as the delivery of email. This API can be used to provide a notification as soon as your users receive an email or to notify them in case there’s an event they should pay attention to. Some concrete examples might be if someone mentions a user in a tweet, or posts a photo of you on Facebook or Google+.

A simple example of use of this API is shown below:

Notification.requestPermission(function() {
   var notification = new Notification('Email received', {
      body: 'You have a total of 3 unread emails'
   });

   notification.onshow = function() {
      console.log('Notification shown');
   };
});

The Web Notifications API is specified by both the W3C specifications and the the WHATWG specifications with some differences between the two versions. In particular, the WHATWG specifications dropped the onclose and the onshow events. So, while the W3C specifications define four events (onclick, onclose, onerror, and onshow), the WHATWG specifications only define two (onclick and onerror).

In case you want to learn more about the different versions of this API and what’s the support of the major browsers you can take a look at my article The state of the Web Notifications API.

Opinion

There aren’t many differences between the specifications but they affect the way you can perform certain tasks. In this case too I’m with the W3C specifications as I think there might be cases to perform actions when the close event is fired which is not possible by following the WHATWG specifications.

Conclusions

In this article we’ve discussed some of the most important differences between the W3C and WHATWG specifications. As you can see, considering the amount of elements and APIs defined in the specifications, there aren’t a lot of differences yet. With this in mind, I’m also not concerned about the future as I’m sure that in the end the specifications will simply match the reality. What this means is that regardless of what was specified by both the groups at the beginning of a feature, browsers and developers have the power to drive the success of one or the other version. So, browsers and developers are the actors that decide which specifications “win” by implementing or adopting them. Because of this, for each feature discussed, the group that will “lose” the battle will end up adapting the specifications to match the reality.

As a final note, in case you want to discover some more differences, you can take a look at the page Differences between the W3C HTML 5.1 specification and the WHATWG LS by the W3C.