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

前端之家收集整理的这篇文章主要介绍了我应该使用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.

原文链接:https://www.f2er.com/html/229929.html

猜你在找的HTML相关文章