3

The following html code is working (Chrome 44, Firefox 37) :

<svg width="100" height="100">

    <script>
        function test() {
            var l= [0,1,2,3];
            console.log(l.length);
        }
    </script>

    <text x="20" y="20" onclick="test()">CLICK ME</text>

</svg>

but this is not :

<svg width="100" height="100">

    <script>
        function test() {
            var l= [0,1,2,3];
            console.log(l.length);
            /*for (var i=0; i<l.length; i++) {
         console.log(i);
            }*/
          }
    </script>

    <text x="20" y="20" onclick="test()">CLICK ME</text>

</svg>

The svg text tag 'CLICK ME' won't even be visible. And the only difference is commented code ! What is the problem ?

Hacketo
  • 4,978
  • 4
  • 19
  • 34
Pmb
  • 33
  • 4
  • Javascript comments in html files can cause these issues if the comments get parsed wrong. Another argument for keeping all javascript in a seperate file instead of mixed in with your html. And if you have to have the javascript inside the html file, keep all script tags as the last tag in the body, so it only gets parsed at the end of the document, after all html nodes have been created. Inline javascript can cause this kind of behavior. – Shilly Aug 21 '15 at 13:59

2 Answers2

3

With your browser you can see how this is parsed, on Chrome I have this result

enter image description here

Actually this is not because of the comment block /* but because of the < that is used in the for-loop that is interpreted as HTML <l.length>

You can use CDATA to avoid that HTML parser parse this piece of code

<svg width="100" height="100">

    <script><![CDATA[
        function test() {
            var l= [0,1,2,3];
            console.log(l.length);
            /*for (var i=0; i<l.length; i++) {
         console.log(i);
            }*/
          }
    ]]></script>

    <text x="20" y="20" onclick="test()">CLICK ME</text>

</svg>

This happens because this <script> element is not exaclty the same element that is defined in HTML. It also provide compatibility with browsers that do not support scripting language, so accoding to W3C it need to be escaped.

Hacketo
  • 4,978
  • 4
  • 19
  • 34
0

Because of coomments Should be so: http://jsfiddle.net/btux9s2d/3/

<svg width="100" height="100">

<script>
    function test() {
        var l= [0,1,2,3];
        console.log(l.length);
       <!--for (var i=0; i<l.length; i++) {
            console.log(i);
        }-->
    }
</script>

<text x="20" y="20" onclick="test()">CLICK ME</text>

</svg>
justtry
  • 639
  • 4
  • 8