我应该使用HTML注释来封装JavaScript代码块吗?

几年前,我被教导嵌入 HTML内的 JavaScript代码块应该总是在HTML注释中被封装如下:
<script type="text/javascript">
<!--
var hello = "world";
-->
</script>

我被告知要这样做,但我从来没有充分想到为什么.使用HTML注释看起来很奇怪,所以现在我已经开始在脚本块中编写我的JavaScript代码,而没有HTML注释:

<script type="text/javascript">
var hello = "world";
</script>

所以我的问题是:我应该使用HTML注释来封装JavaScript代码块?只需编写脚本就可以安全吗?我的意思是说,当我留下评论标签时,我有冒险的东西吗?

解决方法

HTML注释旨在将JavaScript从不了解< script>的古老浏览器中隐藏起来.而是将其内容呈现在页面上.那回到了90年代中期,iirc.如今,您可以放心地认为,那个时代的浏览器不再存在于网络上,而是忽略了这些意见.

有一些很好的历史可以找到here

The general rule regarding HTML tags that browsers do not understand is that the browser should ignore the tag completely and treat the content of the page as if that tag were not there. This means that when netscape 2 first introduced JavaScript (or LiveScript as it was called then),it was necessary to place an HTML comment around the actual script in order to hide the code from other browsers that didn’t understand the script tag and which therefore would have displayed the code rather than running it.

The JavaScript language was specifically written to accept the start of an HTML comment as the very first thing in the script and to ignore it in order that the HTML comment Could be used to hide the script from people using netscape 1,Mozaic,Internet Explorer 1,Internet Explorer 2,and other browsers of similar vintage none of which anyone uses any more. It is these prehistoric browsers (in JavaScript terms) that are meant when you see references in antiquated JavaScript tutorials to wrapping your JavaScript inside an HTML comment in order to hide it from “older” browsers.

With Internet Explorer 3,Microsoft introduced their own equivalent to JavaScript which they call JScript. Since then all browsers have at least recognised the script tag and more modern browsers (netscape 2+,IE3+ etc) the HTML comment is no longer required.so once all your visitors have upgraded to use either netscape 2,Internet Explorer 3,or a more recent browser than either of those two the commenting out of the script becomes redundant code.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些