1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript開始時にあるコメントについて <!-- //-->

Last updated at Posted at 2018-09-01

昔のJavaScriptによくあるコメント

最近はHTMLファイルにJavaScriptを書くことが減ったから、あまり見ないけど…。

<script type="text/javascript">
<!--
  :
//-->
</script>

ある時、JavaScript初心者の方から「このコメント<!-- //-->は何のためにあるのですか?」と聞かれました。

「これはscriptタグが解釈出来ない古いブラウザで表示した時に、JavaScriptのソースが画面に出てしまうのを防ぐものです。」と、説明したところで、ふと疑問に思った。

コメントの終わりは「//」でわざわざJavaScript的にはコメントアウトしているのに、コメントの開始は何もしていない。

検証

以下のコードを試してみた。な、なんと「a」のみ表示されてエラーにならない。

console.log("a")
<!--console.log("b")

仕様

これは、以下のページの真ん中あたりにもあるように、<!--が行コメントとして扱われるそうです。(注: 追記参照)

the string "<!--" in JavaScript is actually treated as a line comment start, just like "//".

https://www.w3.org/TR/html5/scripting-1.html
var a = "<!-- <script>"; がバグるっていう内容も載っていて興味深い。

2018年2月6日追記
もう上記のリンクは死んでいる。インターネットアーカイブの2015年ごろは載っている。ので転記させてもらいます。

  • 4.11.1.2 Restrictions for contents of script elements
<script>
  var example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>
<!-- despite appearances, this is actually part of the script still! -->
<script>
 ... // this is the same script block still...
</script>

</script>が終了しないというバグ

despite appearances, this is actually part of the script still! (外観にもかかわらず、これは実際にまだスクリプトの一部です!)

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?