What's the point of wrapping javascript code in <!-- -->
开发者_如何学JAVA?
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.
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.
check
does javascript code need to start with "<!-- "?
now you don need to wrapping js code in <!-- -->
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.
Older browser that don't understand Javascript will just see an HTML comment.
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.
精彩评论