Why do I need to comment the <script> tag in HTML?

别说谁变了你拦得住时间么 提交于 2019-12-18 05:38:07

问题


Most examples I've seen have scripts in a html page being enclosed by

<!--
...
-->

I've tried writing it without the comment tags and there doesn't seem to be any difference. Why is the comment tag used and what function does it serve?


回答1:


It's not really necessary any more. This has only ever served as a backwards-compatibility hack of sorts - when scripts first started being inserted into static HTML pages, most browsers couldn't support them. Without the comments, they would ignore the semantics of the <script> tag (which they didn't understand), and then would emit the script source onto the page.

Ironically, the solution was a hack in itself - AFAIK, no part of the HTML spec says that script tags should be parsed when inside of comments. The fact that all browsers picked this up seems to be more of a coincidence than anything else. Certainly with XHTML, comments are comments so a fully conformant browser would have to ignore your scripts.

So basically, unless you want to support really, really old browsers (at the cost of breaking some new ones) it's no longer necessary to do this.




回答2:


Really old browsers that didn't understand the <script> tag might assume that it was a formatting tag it didn't understand. They would gracefully fail by rendering the contents of the tag (the script) inline in the page.

By HTML-commenting out the script too those browsers will ignore the content rather than rendering it.

In practice I doubt any of those browsers are still in use and that you can probably get away without the comments nowadays.




回答3:


It's for some old browsers that were in use last century.

You no longer need them any more today, but using CDATA is considered good practice if you write XHTML.




回答4:


It's still a problem nowadays if your page gets processed by a sanitation parser that sanitizes by only rewriting the <script> tag into <xscriptx>. If you leave in the comment tag, then if the script tag gets sanitized, then at least your javascript will still be hidden from the user by the comment tags. If you leave out the comments, the code will be visible.

An example of a sanitation parser is Google Translate, Google Cache or Proxomitron.



来源:https://stackoverflow.com/questions/4421599/why-do-i-need-to-comment-the-script-tag-in-html

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