whatwg / html

HTML Standard
https://html.spec.whatwg.org/multipage/
Other
8.01k stars 2.62k forks source link

Make custom attribute rules consistent with custom element name rules #2271

Open LeaVerou opened 7 years ago

LeaVerou commented 7 years ago

Related WICG discussion: https://discourse.wicg.io/t/relaxing-restrictions-on-custom-attribute-names/1444

Currently, custom attributes need to start with data-. For frameworks with a lot of attributes (Angular, Vue etc), this introduces a serious problem: Either they prefix all attributes with data- and become prone to collisions with other libraries (I've even had two of my own libraries collide!), or they make them extremely verbose (data-ng-*), or they make them non-standard (ng-*, v-*), which is their chosen solution. I'm about to release a library with a lot of attributes and I went for the latter as well. The former two pose serious practical problems, the latter is just conformance.

However, it doesn't have to be this way. Custom elements allow any element name with a hyphen in it, we could do the same for attributes. The cowpaths have been paved: Several very popular libraries follow this practice already. This is not true for proposals like #2250, which introduce a completely new naming scheme.

The main issue with this is all the existing attributes in SVG that come from CSS properties which use hyphens. However, there are several solutions to deal with this:

Marat-Tanalin commented 7 years ago

I’d be fine with this as long as the pre-hyphen part could be empty, so attributes could have names like -foo, -bar, etc.

Otherwise this does not add much over the existing data- prefix (e. g. da- instead of data-) and is probably too problematic compared with the absolutely issue-free and future-proof underscore/hyphen-prefixed custom attributes.

To be fair, better than nothing anyway though.

annevk commented 7 years ago

I'm supportive of this, but only if we also add an API equivalent to what we added for custom elements. It should be possible for folks to easily observe when such attributes are added, removed, and change in value.

zcorpan commented 7 years ago

I’d be fine with this as long as the pre-hyphen part could be empty, so attributes could have names like -foo, -bar, etc.

Starting with a dash is not XML-compatible. Currently the spec requires data-* attribute names to be XML-compatible, and custom element names as well.

LeaVerou commented 7 years ago

Otherwise this does not add much over the existing data- prefix (e. g. da- instead of data-) and is probably too problematic compared with the absolutely issue-free and future-proof underscore/hyphen-prefixed custom attributes.

Clearly, you have not considered collisions between libraries and think everything can have the same prefix and the only problem is how to make the prefix less verbose. I don't blame you, I thought they were an edge case in the past as well, but they absolutely are not. With your proposal, libraries would end up doing things like _ng-*, or (most likely) simply not care and continue using ng-* like they've done for years.

LeaVerou commented 7 years ago

I'm supportive of this, but only if we also add an API equivalent to what we added for custom elements. It should be possible for folks to easily observe when such attributes are added, removed, and change in value.

That would be awesome. So basically, syntactic sugar for MutationObserver?

annevk commented 7 years ago

The problem with MutationObserver for this use case is that you don't know where the attribute is going to be added. So if you want a global custom attribute, you'd have to observe the entire tree and even then you'd miss certain things, such as shadow trees.

Marat-Tanalin commented 7 years ago

@LeaVerou

With your proposal, libraries would end up doing things like _ng-*, or (most likely) simply not care and continue using ng-* like they've done for years.

_ was invalid at the moment of making decisions as for design of those libraries, that’s most likely why libraries’ authors have decided just to drop the (only valid at that moment) data- prefix and not to use a generic prefix that would be formally invalid anyway.

As a side note, it’d probably be wrong to assume that the fact that it’s hard for someone who is already a smoker (existing libraries in terms of custom attributes) to leave off smoking is a reason not to try to prevent others (new products and libraries) from starting smoking (provide a valid short unobtrusive generic prefix).

LeaVerou commented 7 years ago

The problem with MutationObserver for this use case is that you don't know where the attribute is going to be added. So if you want a global custom attribute, you'd have to observe the entire tree and even then you'd miss certain things, such as shadow trees.

True, and what you're proposing would solve a HUGE problem and I would cry tears of joy once it gets implemented! I'm just a bit concerned that it requires considerably more implementor effort, so adding it could stall. Whereas just permitting such attribute names at first would let us use them and it's a super easy addition to the spec since it requires no implementation effort.

annevk commented 7 years ago

Fair, I think there is interest to go in this direction once custom elements has shipped. This idea was briefly discussed at the last W3C TPAC. I think the main thing we lack is someone freeing up the time to write the standard. @domenic thoughts?

rniwa commented 7 years ago

I think the fact custom elements kind of encourage people to add a random attribute is a serious issue already so coming up with a some convention for author-defined attribute is a win even if we couldn't add an API for custom attributes yet.

Having said that, we think custom attribute is a much better alternative to is attribute.

zcorpan commented 7 years ago

Pages in httparchive with attributes that start with _ or non-standard attributes containing -:

SELECT * FROM (
SELECT page, url, REGEXP_EXTRACT(LOWER(body), r'(<[a-z][a-z0-9-]*\s+(?:(?:data-|aria-|http-|accept-)?[a-z]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^>\s/"\']+\s+)|\s+))*(?:_[a-z]|(?:[b-ce-gj-z]|d[b-z0-9]|a[a-bd-qs-z0-9]|h[a-su-z0-9]|da[a-su-z0-9]|ar[a-hj-z0-9]|ac[a-bd-z0-9]|ht[a-su-z0-9])[a-z0-9]*-)[^>\s]*\s*=[^>]*>)') AS match
FROM [httparchive:har.2017_01_01_chrome_requests_bodies]
)
WHERE page = url
AND match != "null"
AND NOT REGEXP_MATCH(match, r'["\']\s*\+') # exclude JS string concats
AND NOT REGEXP_MATCH(match, r'<(altglyph|animate|circle|clippath|color-profile|cursor|defs|desc|ellipse|feblend|fecolor|fediffuse|fedisplacement|fedistant|feflood|fefunc|fegauss|feimage|femerge|femorph|feoffset|fepoint|fespec|fespot|fetile|feturb|filter|font|foreign|g\s|glyph|hkern|image|line|marker|mask|metadata|missing|mpath|path|pattern|polygon|polyline|radial|rect|set\s|stop|svg|switch|symbol|text\s|textpath|tref|tspan|use\s|view\s|vkern)') # exclude SVG elements

4068 results: https://gist.github.com/zcorpan/b54592e415a2f79f2ef7f79c0c37b2ed

Of those:

Other things to note:

zcorpan commented 7 years ago

For comparison, equivalent query for data-* gives 59,755 results. So data-* is about 15 times more common than non-standard custom attributes (excluding _moz_, x-webkit-, x-ms-).

zcorpan commented 7 years ago

So @LeaVerou's proposal is used by ~0.4% of pages in httparchive; @Marat-Tanalin's proposal is used by ~0.1%. data-* is used by ~12.1%. (The data set is 494,956 pages.)

Since the point here is to adopt what people like or use anyway, if we are to do this, it seems most reasonable to me to allow both. But we should disallow _moz_, x-webkit- and x-ms- and 3+ letter prefix followed by dash (to avoid clashes in SVG, and to make it possible to tell if an attribute is a "custom attribute" or not, and to catch typos in aria- or data-), as well as anything not XML-compatible. But no need to restrict the prefix to [a-z], I believe (data-* and custom element names allow other XML-compatible characters).

domenic commented 7 years ago

I still feel there's a strong advantage to sticking to a single sanctioned convention (data-) for custom data attributes, at least until we have a processing model for the "custom attributes".

If people want to go against that convention, that's their choice, but we shouldn't give them a free pass; they're making a conscious choice to trade conformance and ecosystem compatibility for convenience.

Marat-Tanalin commented 7 years ago

@domenic Sorry, but that’s just a purely theoretical statement totally detached from reality.

As a practicing web developer, I’m quite happy with what we already have currently feature-wise: getAttribute() / setAttribute() / removeAttribute() in JS and [attribute] in selectors.

The only issue here is the artificial validity limitation that could and should be easily removed on spec level. Having (or not) a processing model for custom attributes does not affect the ability to use such attributes right now (to be clear: I’m specifically about _-prefixed attributes that are 100% future-proof).

LeaVerou commented 7 years ago

Thanks for the data @zcorpan!! Very enlightening. I find it surprising that Angular and Vue would only be used by 0.4% of websites. Perhaps a lot of these attributes are added dynamically? Also, I'm not surprised that data- has such as high percentage: Small libraries that only add 1 or 2 attributes can easily use data- and be less worried about either collisions or verbosity. It only takes 1 such library for a page to qualify as having a data- attribute.

It's also an interesting idea to allow both proposals. I don't see any problem with that, flexibility is good!

@domenic Several people have commented about the problems with data-. Developers of popular libraries with many attributes are not using data-. Even those that supported both their own prefix- and a data-prefix- version of each attribute are dropping the latter because nobody is using it, probably because data-prefix- is a verbose abomination. And you resist legalizing anything other than data- because of some theoretical purity argument about "a single sanctioned convention"? What happened to the priority of constituencies? Doesn't author convenience come several levels before theoretical purity?!

domenic commented 7 years ago

Several people have commented about the problems with data-. Developers of popular libraries with many attributes are not using data-. Even those that supported both their own prefix- and a data-prefix- version of each attribute are dropping the latter because nobody is using it, probably because data-prefix- is a verbose abomination.

This argument (and I would appreciate if you avoided phrases like "abomination" in reasoned discussion) is based on anecdotes, whereas @zcorpan shows soundly with data that it does not hold in the real world. A small minority of developers using custom attributes are unhappy with data; 15x more are happy with data than are unhappy. They can be vocal, as you are, but saying that this is a widespread problem is just not supported.

And you resist legalizing anything other than data- because of some theoretical purity argument about "a single sanctioned convention"? What happened to the priority of constituencies? Doesn't author convenience come several levels before theoretical purity?!

Sorry, but that’s just a purely theoretical statement totally detached from reality.

I don't think it's helpful or accurate to characterize the argument as one of theoretical purity, or start invoking the priority of constituencies before any such violation is apparent. This is about the practical impact of fracturing the ecosystem into multiple conventions for custom data. That has real impact on tooling, libraries, authors reading other authors' source code, API consistency and predictability (why do some data properties get a dataset API, and others don't?) and much more.


Again, I repeat that there is nothing stopping you from making a conscious choice between conformance and brevity. If you value brevity so much as to start calling data- attributes an abomination, I presume you value it more than conformant documents. That's fine! You can make that choice! As you yourself have noted, there's nothing stopping you. But it doesn't mean the spec should stop trying to keep the ecosystem coherent to the best of its abilities.

Marat-Tanalin commented 7 years ago

@domenic

15x more are happy with data than are unhappy.

The obvious reason of prevalence of data--prefixed attributes over other prefixes is that data- is the only formally valid option for now. This has nothing to do with whether people are actually happy with it.

Good web developers just usually prefer to keep their documents valid, and not just because that makes them “feel good”, but also to be able to use validators to easier see real errors not intermixed with fictious pseudoerrors related to artificial spec-level limitations not matching reality.

why do some data properties get a dataset API, and others don't?

Because not all custom attributes are data attributes. data- attributes are for data, custom-prefixed attributes are for custom needs whatever those are.

stevefaulkner commented 7 years ago

@zcorpan wrote:

So @LeaVerou's proposal is used by ~0.4% of pages in httparchive; @Marat-Tanalin's proposal is used by ~0.1%. data-* is used by ~12.1%. (The data set is 494,956 pages.)

does that mean that some other form of prefix is used by the other 87%?

domenic commented 7 years ago

The obvious reason of prevalence of data--prefixed attributes over other prefixes is that data- is the only formally valid option for now. This has nothing to do with whether people are actually happy with it.

That's an interesting speculation. Fortunately, it's also one we can answer, or at least upper-bound, with data. That is, what percentage of those ~12.1% of pages are conformant? In other words, what percentage of people using data-* attributes are also people who care about conformance, and thus might have chosen data- over x- because of conformance concerns?

Similarly, what percentage of the ~0.5% using nonstandard prefixes are conformant-except-for-bad-prefixes? This number is especially interesting, because it indicates people who are interested in conformance but just aren't willing to change their prefixes. Certainly you and Lea might fall in that sub-bucket of the ~0.5%. (Although maybe not?) But how many of that ~0.5% are you representing?


Another point worth making is the analogy to a previous push to use <i> for icons. The reasoning was exactly the same: lots of people are doing it, because it's shorter than the recommendation in the spec (<span> with fallback text). We even did a HTTP archive search, and found that many more developers would "benefit" from allowing this than the fraction-of-~0.5% being discussed here. But allowing <i> for icons has many practical downsides---the same ones I listed before for allowing non-data- prefixes for custom data attributes. For that reason, we didn't do it.


does that mean that some other form of prefix is used by the other 87%?

I assume it means they are not using any prefixed attributes (data- or otherwise) at all.

domenic commented 7 years ago

Let me also repeat that I do support exploring the concept of custom attributes, with a processing model similar to custom elements. That gives serious benefits beyond just brevity, that IMO outweigh the practical disadvantages. It's the simple conformance change with no processing model that I am not in support of.

LeaVerou commented 7 years ago

Again, I repeat that there is nothing stopping you from making a conscious choice between conformance and brevity. If you value brevity so much as to start calling data- attributes an abomination, I presume you value it more than conformant documents. That's fine! You can make that choice! As you yourself have noted, there's nothing stopping you. But it doesn't mean the spec should stop trying to keep the ecosystem coherent to the best of its abilities. @Marat-Tanalin

Authors don't typically invent their own attributes, and when they do, data- is fine. Most custom attributes are used because a library/framework will utilize them. Therefore, the person using the attribute is not the same person that decided on its naming. It's not about my choice, it's about making the right choice for the users of my library. I don't want to impose verbosity on them and litter their markup with lengthy prefixes, and I don't want to impose nonconformance on them. Library devs should not be forced into this dilemma.

Re: fracturing the ecosystem, how does that not apply to custom element names?

whereas @zcorpan shows soundly with data that it does not hold in the real world

While I definitely commend the effort to get real data, I would take that percentage with a grain of salt:

  1. We're basically parsing HTML with regexes here
  2. None of this accounts for dynamically added attributes.
  3. It counts occurrence of each naming scheme per page, whereas I suspect that when ng- or v- attributes are used, A LOT of them are used.
  4. As I mentioned above, smaller libraries can use data- just fine. When you only have one or two attributes, the verbosity doesn't matter much and the collisions are more rare. It only takes 1 such library for a page to count in @zcorpan's data.
  5. As @Marat-Tanalin mentioned, data- is the only conformant option right now, don't you think that affects usage?
  6. These stats go against common knowledge: Angular and Vue are very popular, it seems weird that they'd be collectively used by only 0.4% of websites.

Fortunately, it's also one we can answer with data. That is, what percentage of those ~12.1% of pages are conformant? In other words, what percentage of people using data-* attributes are also people who care about conformance, and thus might have chosen data- over x- because of conformance concerns?

You're assuming here that everybody who cares about conformance is actually conformant. A parallel about religions and sins comes to mind. :) Many authors care about conformance, but don't actually validate, so they make mistakes that are never caught. However, conformance still influences their decision making.

LeaVerou commented 7 years ago

Let me also repeat that I do support exploring the concept of custom attributes, with a processing model similar to custom elements. That gives serious benefits beyond just brevity, that IMO outweigh the practical disadvantages. It's the simple conformance change with no processing model that I am not in support of.

Nobody is against that. As I said above, that would be incredible! It would make my life so much easier. What I was suggesting is making the conformance change first, since it's easy, and adding the (harder to design) API as a later step, once it gets implementor interest and a spec editor willing to do it.

Marat-Tanalin commented 7 years ago

@domenic

(Although maybe not?)

I would appreciate if you avoided further trolling.

FYI, unlike what you’ve probably naively assumed, I am aware the pubdate attribute is currently not in the HTML spec, so using the formally invalid attribute is not accidental. I use the attribute intentionally since it was previously specced and perfectly valid, but then has been removed on a purely theoretical basis by someone who unfortunately has a sort of overformal logical approach (but who is still able to be respectful and deserves to be respected) somewhat similar to yours, and recommended to use the bolted-on verbose pseudosemantic surrogate called Microdata instead. (Btw, the same person also tried to remove the TIME element in favor of a new cool universal element called… DATA, but fortunately failed thanks to massive web-developers’ objections.) Violating the current version of the HTML spec by continuing to use the pubdate attribute solely on my own site is a sort of my conscious and consistent objection to that (wrong in my opinion) decision. Moreover, according to my experience, at least Google search engine does support the attribute regardless of that it has been removed from the spec, so its use still makes sense in practice.

Marat-Tanalin commented 7 years ago

Another point worth making is the analogy to a previous push to use <i> for icons.

Any analogy suffers from inaccuracies, is not a proof or an argument of any kind, and is often actually just irrelevant offtopic noise.

Hixie commented 7 years ago

Let's please remain focused on the technical issues.

zcorpan commented 7 years ago

@Marat-Tanalin

Because not all custom attributes are data attributes. data- attributes are for data, custom-prefixed attributes are for custom needs whatever those are.

I think this is incorrect (as I also said in https://github.com/whatwg/html/issues/2250#issuecomment-271479610). There is no difference in intended use at all -- why would there be? Possibly we should tweak the spec text to clarify that it is not "wrong" to use data-foo as a "boolean" attribute, etc. I can work on a PR for that. What other usages for "custom attributes" are there that you think are not "data"?

Marat-Tanalin commented 7 years ago

@zcorpan Is the disabled attribute a data attribute? (Fwiw, it is clear to me that boolean data- attributes are valid per spec.)

WebReflection commented 7 years ago

FWIW, the moment data-* shipped is the moment pretty much every old fashioned MVC library added data-bind to any node, knockout to name one, others following, causing the same name clashing problem data- was supposed to solve for HTML attributes, but in developers-land (TL;DR the problem just moved somewhere else)

Being also impossible to polyfill, in terms of el.dataset.name and similar Proxy kind of sorcery, most advantages initially thought for developers got lost in "trans(pi)lation", since it was still a el.get/setAttribute('data-whatever') matter, which is probably in the Top Ten things I really don't want to waste time anymore typing in my life ... but that's another story, sorry ...

That being said, there's a lot of legacy in the wild trusting data-attributes and aria-roles are also untouchable from a "don't break the Web" point of view, so I agree with @domenic there's no way we can just throw away data- and aria- like that, and we honestly shouldn't.

However, since the begninning of the time, Custom Elements had reserved names such:

annotation-xml
color-profile
font-face
font-face-src
font-face-uri
font-face-format
font-face-name
missing-glyph

Proposing a new attribute standard that define forbidden prefixes for attributes doesn't seem that different, as long as the provided data is realiable and there are really no huge conflicts with what's already used out there. For instance, I know some major player use prefixes that are not mentioned in here, only because their prefixes are behind the scene, and not public. Having browser breaking randomly prefixes that don't show up on the Open Web is not probably "good enough".

Good news is: these kind of changes don't happen over night, so if there is a will to promote custom attributes, providing a list of untouchable prefixes so that other can have time to eventually update their code-base, that'd be ace.

Not A Substitute for Native Extends

I am not sure whi @rniwa mentioned it, but this proposal has nothing to do with the is="custom-el" one.

Attributes are per element, unless you want every website to add a MutationObserver to the document.documentElement so that every custom attribute would be intercepted and its node somehow manifested, including Shadow DOM concerns already mentioned, there's no way this is going to solve anything at all regarding the ability to define Custom Elements that extends natives: you would still need to declare a prototype that should react when that kind of node only had a custom attribute changed.

Possible Custom Element Seppuku

One thing to be concerned about, is the dual binding at that point a custom prefixed attribute is going to be readable, and writable, through the element. In current Custom Element specifications, if I have ['my-attr'] as list of observable attributes, I expect that whoever use setAttribute on it would trigger an attributeChangdCallback. If I have something reflected per instance that as soon as accessed would eventually trigger a possible callback, we'll be in infinite loop/recursion land for a basic attribute set, something that at least el.dataset.attrName = "value" wouldn't cause.

As summary, I hope this proposal/idea will be implemented, considering all the possible side-effects it might bring to the table (and not because the proposal is bad, simply because we have legacy around the WWW :-( )

zcorpan commented 7 years ago

@Marat-Tanalin it's not a custom attribute, so I don't understand the relevance to what I said. I did not say that standard boolean attributes are "data". I said that data-* attributes are not just for "data", but for any custom use, like you want to use _foo attributes for. So again, what do you want to use _foo for that you do not consider "data"?

zcorpan commented 7 years ago

@LeaVerou

These stats go against common knowledge: Angular and Vue are very popular, it seems weird that they'd be collectively used by only 0.4% of websites.

SELECT page, COUNT(url) AS num
FROM [httparchive:har.2017_01_01_chrome_requests] WHERE
REGEXP_MATCH(JSON_EXTRACT(payload, '$.request.url'), '/(angular|vue).+js')
AND JSON_EXTRACT(payload, '$.response.content.mimeType') CONTAINS 'javascript' 
GROUP BY page
ORDER BY num DESC

5841 pages, so ~1.2%. Per https://trends.builtwith.com/javascript/Angular-JS it should be something like 1.4% in top 1m sites using Angular, so this seems in the right ballpark.

Marat-Tanalin commented 7 years ago

@zcorpan Simon, thank you for your substantive comments and questions.

it's not a custom attribute, so I don't understand the relevance to what I said.

My point is that all custom attributes are data attributes to the same extent as all standard attributes are data attributes. The latter are obviously not, so the former are not too.

what do you want to use _foo for that you do not consider "data"?

Given that _-prefixed attributes are currently formally invalid and I care about validity, I add them only via JS for now, so they are not discoverable by validator. This primarily includes adding attributes to the root HTML element dynamically based on feature detection for the purpose of applying different styles depending on what features are available. Using classes for the HTML element for this purpose is undesirable since such classes could conflict with other elements’ classes given that it’s a good CSS practice, in stylesheets, not to prepend class selector with a specific-element selector when styles are for a generic DIV container (e. g. just .foo should be used instead of DIV.foo, while the HTML element could have the foo class too, so styles could be unintentionally applied to the HTML element too). To prevent collisions, a prefix should be added to the class name (so that HTML-element’s class is named _foo instead foo), but then there is no point in using a class (<html class="_foo">), and it’s easier just to add a same-name prefixed attribute (<html _foo>). Compared with data- attributes, _ is shorter and makes selectors in CSS easier to read and use ([_foo] instead of [data-foo]) regardless of whether the attributes are added dynamically (and not hard-coded statically) on HTML level.

Also, using attributes in terms of feature detection allows to have more than just two boolean states (available/unavailable) that, in case of a class, would need to have a bunch of different similar classes, while an attribute, unlike a class, has not just a name, but also a value (this specific benefit applies to data- attributes too, but they are just too long as we already know).

Another purpose I would use _-prefixed attributes for once they are legitimized is e. g. navigation menus where design needs to apply styles to previous element of a specific element (e. g. corresponding to current section of the site). Given that there is still no way to select the previous sibling (unlike next sibling), it’s solved by marking the corresponding previous element explicitly on HTML level either with a class or with an attribute. With a class, to prevent collisions with global classes, it would make sense to use a local class prefixed with e. g. _, but if I’m forced to use a prefix anyway, it’d be unreasonable to use a class if a same-name attribute could be used instead:

<li class="_prev"><li _prev>

As a bonus, compared with classes, attributes allow more possibilities in terms of selectors, e. g. it’s possible to select elements by a part of an attribute. And compared with the one-character _ prefix, the data- prefix is too long and obtrusive as already said by me and others.

zcorpan commented 7 years ago

My point is that all custom attributes are data attributes to the same extent as all standard attributes are data attributes. The latter are obviously not, so the former are not too.

OK, so it seems we agree on this.

Thanks for the examples. I'll try to tweak the spec text and add new examples in the spec for data-* attributes.

chaoaretasty commented 7 years ago

If both proposals are being looked at perhaps it would be worth adding a note discouraging use of underscore prefix in libraries but to reserve it for individual sites and page level javascript. If this is done at the level of SHOULD/SHOULD NOT it won't affect conformance but will hopefully encourage good practice (and avoid the worst scenario where the first library using underscore to get popular will end up owning it).

This actually then has a nice benefit of making it easy to see attributes that are part of a library vs ones aimed at more local use.

zcorpan commented 7 years ago

That sounds reasonable; the spec already has this text for data-* and JS libraries:

JavaScript libraries may use the custom data attributes, as they are considered to be part of the page on which they are used. Authors of libraries that are reused by many authors are encouraged to include their name in the attribute names, to reduce the risk of clashes. Where it makes sense, library authors are also encouraged to make the exact name used in the attribute names customizable, so that libraries whose authors unknowingly picked the same name can be used on the same page, and so that multiple versions of a particular library can be used on the same page even when those versions are not mutually compatible.

For example, a library called "DoQuery" could use attribute names like data-doquery-range, and a library called "jJo" could use attributes names like data-jjo-range. The jJo library could also provide an API to set which prefix to use (e.g. J.setDataPrefix('j2'), making the attributes have names like data-j2-range).

https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes

digeomel commented 7 years ago

Don't want to weigh in on the discussion, but from a practical Web developer's point of view, we have a disagreement with our colleagues at the office related to your subject. We are creating our own custom Angular components (e.g. <my-dropdown>) and we are wondering how to name the custom attributes for these. One colleague is putting data- all over them, because he's concerned about the validation issues, and I suggested that this is pointless, since strict, old-fashioned validators will complain about the custom elements anyway, so what's the point of prefixing the attributes with data-?

I would appreciate some advice on this. Thanks :)

zcorpan commented 7 years ago

You could use https://checker.html5.org/ which supports custom elements.

The reason arbitrary attributes are not allowed on custom elements is that standard global attributes apply to custom elements as well, and they are not a frozen set; we want to keep the possibility to add new attributes to the standard without conflicting with existing web content that had already started using that name for something else. So data- for custom elements is correct.

zcorpan commented 7 years ago

Sorry, my above comment is wrong for autonomous custom elements, they allow any attribute per the HTML standard (and the checker allows them as well). See https://html.spec.whatwg.org/#autonomous-custom-element . The possible conflict with any new global attributes is still there, but is also there for the embed element...

chaoaretasty commented 7 years ago

Based on the current discussions the recommendations would be:

Marat-Tanalin commented 7 years ago

data-my-attribute - existing data prefix but also good practice of including a namespace for your attributes

This one looks redundant.

Also, it would probably make sense to generally recommend to use the _ prefix for any (incl. library-specific) nonstandard attributes, and additionally use a library-specific prefix for libraries. So if a New Cool Framework has appeared and it needs HTML attributes, its prefix would be e. g. _ncf-. Two-characters prefix space would be exhausted very quickly, while with _, we would have an unlimited number of possible framework-specific prefixes.

nuxodin commented 7 years ago

Any news on this? There is no good reason why tags can be custom but attributes not.

Marat-Tanalin commented 7 years ago

Fwiw, I’ve already started using _-prefixed custom attributes instead of data- attributes and local classes.

Update: I mean using now in static HTML — besides adding dynamically via JS that I did long ago before public proposal.

LeaVerou commented 7 years ago

Fwiw, I’ve already started using _-prefixed custom attributes instead of data- attributes and local classes.

I've been using mv- attributes in a library I'm about to release since before I started this post, doing my part in paving the cowpaths even more :)

strongholdmedia commented 7 years ago

I’d be fine with this as long as the pre-hyphen part could be empty, so attributes could have names like -foo, -bar, etc.

I'd rather support your proposal, as it is generic and not biased (towards angular or whatever). I also have the personal preference of the dash over the underscore (the latter just looks uglier to me). But please remember that many X(HT)ML parsers follow the XML syntax that mandates that XML names may start with a letter, an underscore, or a colon (!) only. Should this change be implemented as is, that might break a lot of things. (In an era when one has to fight for people to close tags like<img />, <br /> properly, it does matter to me.) On the other hand, attributes starting with a colon shall work with XML based stuff, and according to my test they also work in Firefox properly, however there may be quirks with other user agents / DOM implementations.

fregante commented 7 years ago

Dumb question: does XML compatibility matter at all? HTML5 is not XML already.

Also I'd add that today we can have data-* and aria-* attributes only because nobody squatted on those before. If people start using random attributes we'll reach a point where you can't introduce attributes with "nice" prefixes because they'd conflict with existing sites.

I'd love -myattr, I'd be ok with _myattr, but I see the suggestion to open any dashed attribute as shortsighted.

What I really liked was the good ol' real namespaces of XML, where you'd define your namespace:* at the top and avoid any conflicts.

zcorpan commented 7 years ago

Re XML compatibility, see https://github.com/whatwg/html/pull/1356#issuecomment-224088877 and earlier comments.

In this case, attribute names are important to preserve and be able to work with without having to go through infoset coersion. So in my opinion the general rule to be XML compatible should apply.

nuxodin commented 7 years ago

Can someone set it in stone?

domenic commented 7 years ago

So far none of the arguments here have sufficed to convince the editors or address their objections in a satisfactory way, so no. See https://github.com/whatwg/html/issues/2271#issuecomment-273839370 for my latest thinking, at least. In fact it maybe time to close the issue without action.

Marat-Tanalin commented 7 years ago

Probably the best option is just to use the feature since it just works in all browsers regardless of what the spec says.

fregante commented 7 years ago

Sure, why not

  1. Willingly risk things breaking in the future
  2. Cause headaches for spec authors who will have to work around stubborn library authors' decisions?