31

I just curious why my JavaScript can't run (tested in Firefox and IE) if I write the <script> tag like this:

<script type="text/javascript" src="script.js"/>

It will work if I change that line to:

<script type="text/javascript" src="script.js"></script>

So my question is: why I can't close the script tag in the start tag since I don't have any content inside it.

My JavaScript code is simple, just:

alert("test");

Notes: I check firefox error console and no error.

Iswanto San
  • 18,263
  • 13
  • 58
  • 79
  • 1
    Script can't enclose itself. It's just that way. All DOM-elements that "can" have innerHTML, can't be closed on itself. –  Apr 09 '13 at 08:52
  • Compatibility depends on the _doctype_ - see http://stackoverflow.com/questions/97522/what-are-all-the-valid-self-closing-elements-in-xhtml-as-implemented-by-the-maj but browsers still vary on supporting self closing `` – andyb Apr 09 '13 at 08:53
  • @andyb — No, it doesn't. *Validity* does. Compatibility depends on *content-type*. – Quentin Apr 09 '13 at 09:00
  • @Quentin Yes, I completely agree. A very poor word choice in my comment. – andyb Apr 09 '13 at 09:03
  • HTML tags are either self closing or not. It has nothing to do with the / at the end. That's an XML thing, not an HTML thing. So for example – PHP Guru Feb 17 '20 at 17:26

2 Answers2

17

The concept of self-closing tags is an XML concept. You can't use them in HTML. (You can use them in XHTML, but only if the document is served with an XML content-type, not if it is served as text/html).

In HTML some elements (such as <img>) cannot have any content, so they don't have end tags).

Since a script can have a src attribute or the script be can inside the element, <script> is not one of them.

(HTML 5 allows a / character to appear at the end of a start tag for an element that is defined as EMPTY, but it is just sugar for people addicted to XML and has no meaning in the language).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Can I use ``? – Iswanto San Apr 09 '13 at 09:01
  • 4
    No. `meta http-equiv` is a joke. You need a real HTTP header. You also need the correct content type (which is `application/xhtml+xml`). You should also use UTF-8, ISO-8859 has been long since superseded. I'd also recommend against XHTML since it will give you worse browser support, worse performance in browsers that do support it, and it sacrifices clean recovery from markup errors. – Quentin Apr 09 '13 at 09:03
  • One more question, what do you mean `meta http-equiv` is a joke? – Iswanto San Apr 09 '13 at 09:04
  • Because it is so far from being equivalent that you have to laugh (or cry). – Quentin Apr 09 '13 at 09:06
-2

maybe u are using HTML 5 doctype, use html 4 doctype for this

strike_noir
  • 4,080
  • 11
  • 57
  • 100