HTML5: which is better - using a character entity vs using a character directly?

拜拜、爱过 提交于 2019-12-03 06:40:20

问题


I've recently noticed a lot of high profile sites using characters directly in their source, eg:

<q>“Hi there”</q>

Rather than:

<q>&ldquo;Hi there&rdquo;</q>

Which of these is preferred? I've always used entities in the past, but using the character directly seems more readable, and would seem to be OK in a Unicode document.


回答1:


If the encoding is UTF-8, the normal characters will work fine, and there is no reason not to use them. Browsers that don't support UTF-8 will have lots of other issues while displaying a modern webpage, so don't worry about that.

So it is easier and more readable to use the characters and I would prefer to do so.

It also saves a couple of bytes which is good, although there is much more to gain by using compression and minification.




回答2:


The main advantage I can see with encoding characters is that they'll look right, even if the page is interpreted as ASCII.

For example, if your page is just a raw HTML file, the default settings on some servers would be to serve it as text/html; charset=ISO-8859-1 (the default in HTTP 1.1). Even if you set the meta tag for content-type, the HTTP header has higher priority.

Whether this matters depends on how likely the page is to be served by a misconfigured server.




回答3:


Using characters directly. They are easier to read in the source (which is important as people do have to edit them!) and require less bandwidth.




回答4:


The example given is definitely wrong, in theory as well as in practice, in HTML5 and in HTML 4. For example, the HTML5 discussions of q markup says: “Quotation punctuation (such as quotation marks) that is quoting the contents of the element must not appear immediately before, after, or inside q elements; they will be inserted into the rendering by the user agent.”

That is, use either ´q’ markup or punctuation marks, not both. The latter is better on all practical accounts.

Regarding the issue of characters vs. entity references, the former are preferable for readability, but then you need to know how to save the data as UTF-8 and declare the encoding properly. It’s not rocket science, and usually better. But if your authoring environment is UTF-8 hostile, you need not be ashamed of using entity references.




回答5:


It is better to use characters directly. They make for: easier to read code.

google's HTML style guides advocates for the same.The guide can be found here: Google HTML/CSS Style guide



来源:https://stackoverflow.com/questions/9808098/html5-which-is-better-using-a-character-entity-vs-using-a-character-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!