Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The primary answer is: Use JavaScript files for JavaScript, not HTML files, and use the <code>src</code> attribute of script tags. (Combine all your JS into one file, minimize, gzip, etc. for performance.)</p> <p>But, you <em>can</em> embed JavaScript in HTML if absolutely necessary. Use a valid, modern DOCTYPE and you don't have to resort to comment tags and CDATA sections.</p> <p>Valid HTML5 example:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-type" content="text/html;charset=UTF-8"&gt; &lt;title&gt;Example&lt;/title&gt; &lt;script type='text/javascript'&gt; function foo() { var a = 1, b = 2; if (a &amp;&amp; b) { alert("Both"); } if (a &lt; b) { alert("a &lt; b"); } if (a &gt; b) { alert("a &gt; b"); } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;Hi there&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>That will also validate as HTML4 strict if you change the doctype to</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; </code></pre> <p>Note that in both cases, you need to be careful about end tags in your script --</p> <p>This causes the problem:</p> <pre><code>&lt;script type='text/javascript'&gt; alert("&lt;/td&gt;"); &lt;/script&gt; </code></pre> <p>This solves the problem by prefacing the slash with a backslash (or you can break the end tag up into separate string literals):</p> <pre><code>&lt;script type='text/javascript'&gt; alert("&lt;\/td&gt;"); // -or- alert("&lt;" + "/td&gt;"); &lt;/script&gt; </code></pre> <p>But again, the basic answer is: Don't embed JavaScript within HTML files when you can avoid it, use JavaScript files for that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload