Wrapping javascript in <!— -->

前端 未结 6 916
慢半拍i
慢半拍i 2021-02-13 02:15

What\'s the point of wrapping javascript code in ?

相关标签:
6条回答
  • 2021-02-13 02:51

    It prevents user agents that are either not aware of the <script> tag or do not handle it properly from trying to parse or display JavaScript code as HTML.

    It's common perception that you have to travel to the late 1990's to find a browser that's unaware of the <script> tag. However, my own sites are often spidered by tools that implement very rudimentary parsers (why not? You can write a grabber with 10 lines of PHP). And I've also found JavaScript code showing up in the middle of a document after pasting from a web site into a desktop app that's supposed to accept HTML from the clipboard. Thus, escaping non-HTML contents in HTML comments is not as silly as it may seem.

    0 讨论(0)
  • 2021-02-13 03:03

    Apart from some browsers possibly not supporting it there is another reason: the W3C XHTML validator (http://validator.w3.org) interprets JavaScript that is not in comment tags as if it were HTML. So something like "i < 0" will mean your website doesn't validate unless you use these tags.

    0 讨论(0)
  • 2021-02-13 03:06

    This is one of my pet peeves. This is an ancient developer practice to "protect" older browsers that didn't understand <script> tags. Without it, they might fail to load the page or display the script content as html content.

    But we're talking ancient browsers here. The only browsers that ever failed on parsing javascript were 1995 era browsers. These browsers are simply not in use today. This practice is just a holdover from 90's era web development.

    No one should ever be putting <!-- --> blocks around their script tag content anymore.

    If you see developers that are still doing this, please correct them. Not parsing javascript hasn't been an issue since Netscape 1.0, and this practice is actually considered harmful for modern browsers.

    0 讨论(0)
  • 2021-02-13 03:07

    Older browser that don't understand Javascript will just see an HTML comment.

    0 讨论(0)
  • 2021-02-13 03:12

    By wrapping Javascript code in an HTML comment, you prevent older browsers that do not support Javascript from trying to treat the code as HTML.

    0 讨论(0)
  • 2021-02-13 03:12

    check

    does javascript code need to start with "<!-- "?

    now you don need to wrapping js code in <!-- -->

    0 讨论(0)
提交回复
热议问题