Why don't self-closing script elements work?
Asked Answered
A

12

1521

What is the reason browsers do not correctly recognize:

<script src="foobar.js" /> <!-- self-closing script element -->

Only this is recognized:

<script src="foobar.js"></script>

Does this break the concept of XHTML support?

Note: This statement is correct at least for all IE (6-8 beta 2).

Annabelle answered 16/9, 2008 at 6:52 Comment(14)
I assume that you're talking about proper XHTML? couple of comments are still talking about XHTMLPrintable
Works in Chrome and OperaWatersoak
Also, see this question: #349236Kela
Some recent version of Chrome appears to have broken this, self-closing script tags no longer work in ChromeMcilroy
It isn't just script tags. I don't believe self-closing div tags work either.Hexateuch
As of July 2011, Chrome and Firefox have this problem. "It's not a bug, it's a feature" - really annoying.Hagiology
XHTML5 self-closing tagsRussellrusset
I only use self-closing tags for images or inputs because I know the rest can be unsupported in some browsers.Ashes
The more general version of this was asked two days later: #98022Hereunto
Also, in some versions of Chrome (at least mine, currently 34.0.1847.116) not only will the script in the self closing tag fail to load, but it can break script nodes defined in distant document locations (e.g. <script>s in <body> even though the self-closed <script> was in <head>)Buccinator
See also: A Detailed Breakdown of the <script> TagTelescope
Asked in 2008 and still confuses people to this day, me included.Haya
I think behind this question is an assumption that XHTML is just a well-formed subset of HTML. But in reality, XML's use of <foo /> for self-closing tags does not actually exist in HTML. Tag behaviours are defined by the HTML spec. Web browsers already know e.g. that <img> and<br> self-close and <div> and <script> don't, so they don't rely on the presence or absence of /.Expropriate
Modern reference - companies and people are getting on board to document all this in one place, Microsoft has also endorsed this going forward as the reference to use. developer.mozilla.org/en-US/docs/Web/HTML/Element/scriptImprest
P
518

The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:

С.3. Element Minimization and Empty Element Content

Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p />).

XHTML DTD specifies script elements as:

<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
Printable answered 16/9, 2008 at 7:8 Comment(11)
Still, “do not” isn't the same as “must not”. This is a guideline (for compatibility, as suggested by the section title), not a rule.Voussoir
Actually, I can't find any use for this restriction :) It seems completely artificial.Printable
The right answer was given by olavk. The Appendix C of XHTML 1.0 isn’t the reason why things are the way they are—it just how to work around the way things are.Rigging
It's not a normative part of specification. It's only appendix about how to deal with browsers that do not support XHTMLThriftless
nevertherless, browsers do understand <p/> notation pretty well.Claudieclaudina
The problem with <script /> is not that the spec disallows it, but that browsers don't interpret it as "non-tag-soup" if the content type is not application/xhtml+xml. See: #349236 @shabunc: browsers may appear to understand it, but what's actually happening is it's putting the content after the <p/> inside the paragraph, due to interpreting squadette's quote to mean that since <p> is non-empty, it can't be self-closing. In XHTML 1.1, it can be self-closing.Rayerayfield
4.3. For non-empty elements, end tags are required - XHTML 1.0: The Extensible HyperText Markup Language (Second Edition): ... All elements other than those declared in the DTD as EMPTY must have an end tag. Elements that are declared in the DTD as EMPTY can have an end tag or can use empty element shorthandInflux
@JeremyKao 4.3 is not relevant here. (see the examples) Scroll down to 4.6 for the rule closer to what we are discussing.Compassionate
This is some kind of dumb IT-bureaucracy. Obviously normal people expect this to work/to be supported. Obviously parsers and interpreters could deal with this. Or at least give an error in console. When you do self-closed script, the whole page wont work and no error is shown. But then <body onload="start()" /> works fine.Rebozo
@Rebozo - There is no "bureaucracy" to blame. See greim's answer for a historical note, as to why it was done this way.. See joelhardi's answer re how to improve the situation, by sending a different mimetype.Lunna
Why can't <script> be used by itself? If is specifies a src attribute, it has no content, so it does not need </script> at all.Flavio
Y
256

To add to what Brad and squadette have said, the self-closing XML syntax <script /> actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml in the HTTP Content-Type header (and not as text/html).

However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html.

From w3:

In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family documents, and the use of 'text/html' SHOULD be limited to HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml' MAY also be used, but whenever appropriate, 'application/xhtml+xml' SHOULD be used rather than those generic XML media types.

I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script> syntax with text/html (HTML syntax + HTML mimetype).

If your server sends the text/html type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script /> will not work (this is a change, Firefox was previously less strict).

This will happen regardless of any fiddling with http-equiv meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />.

Yearn answered 16/9, 2008 at 8:14 Comment(4)
Is it correct then to conclude that if you drop support for IE7, sending text/xml will get you broad browser support for <script/> ?Despotism
So, in short, <script/> will work only if your MIME type of the page is xhtml/xml. For regular text/html pages, it won't work. AND if we do try to use "xhtml/xml" MIME type, it will break IE compatibility. To summarize, Keep Calm and Use <script> ... </script> Thanks Joe ;-)Yuriyuria
Excellent explanation. Another point worth noticing is that Firefox will also have local .html files rendered as a tag-soup regardless of meta tags, for similar reasons. For XHTML files, Firefox will only render them accordingly if they're named .xhtml.Anticoagulant
@ChrisMoschini. Probably, but use application/xhtml+xml, not text/xml.Seraphic
S
219

Others have answered "how" and quoted spec. Here is the real story of "why no <script/>", after many hours digging into bug reports and mailing lists.


HTML 4

HTML 4 is based on SGML.

SGML has some shorttags, such as <BR//, <B>text</>, <B/text/, or <OL<LI>item</LI</OL>. XML takes the first form, redefines the ending as ">" (SGML is flexible), so that it becomes <BR/>.

However, HTML did not redefine this, so <SCRIPT/> should mean <SCRIPT>>.
(Yes, the '>' should be part of content, and the tag is still not closed.)

Obviously, this is incompatible with XHTML and will break many sites (by the time browsers were mature enough to care about this), so nobody implemented shorttags and the specification advises against them.

Effectively, all 'working' self-ended tags are tags with prohibited end tag on technically non-conformant parsers and are in fact invalid. It was W3C which came up with this hack to help transitioning to XHTML by making it HTML-compatible.

And <script>'s end tag is not prohibited.

"Self-ending" tag is a hack in HTML 4 and is meaningless.


HTML 5

HTML5 has five types of tags and only 'void' and 'foreign' tags are allowed to be self-closing.

Because <script> is not void (it may have content) and is not foreign (like MathML or SVG), <script> cannot be self-closed, regardless of how you use it.

But why? Can't they regard it as foreign, make special case, or something?

HTML 5 aims to be backward-compatible with implementations of HTML 4 and XHTML 1. It is not based on SGML or XML; its syntax is mainly concerned with documenting and uniting the implementations. (This is why <br/> <hr/> etc. are valid HTML 5 despite being invalid HTML4.)

Self-closing <script> is one of the tags where implementations used to differ. It used to work in Chrome, Safari, and Opera; to my knowledge it never worked in Internet Explorer or Firefox.

This was discussed when HTML 5 was being drafted and got rejected because it breaks browser compatibility. Webpages that self-close script tag may not render correctly (if at all) in old browsers. There were other proposals, but they can't solve the compatibility problem either.

After the draft was released, WebKit updated the parser to be in conformance.

Self-closing <script> does not happen in HTML 5 because of backward compatibility to HTML 4 and XHTML 1.


XHTML 1 / XHTML 5

When really served as XHTML, <script/> is really closed, as other answers have stated.

Except that the spec says it should have worked when served as HTML:

XHTML Documents ... may be labeled with the Internet Media Type "text/html" [RFC2854], as they are compatible with most HTML browsers.

So, what happened?

People asked Mozilla to let Firefox parse conforming documents as XHTML regardless of the specified content header (known as content sniffing). This would have allowed self-closing scripts, and content sniffing was necessary anyway because web hosters were not mature enough to serve the correct header; IE was good at it.

If the first browser war didn't end with IE 6, XHTML may have been on the list, too. But it did end. And IE 6 has a problem with XHTML. In fact IE did not support the correct MIME type at all, forcing everyone to use text/html for XHTML because IE held major market share for a whole decade.

And also content sniffing can be really bad and people are saying it should be stopped.

Finally, it turns out that the W3C didn't mean XHTML to be sniffable: the document is both, HTML and XHTML, and Content-Type rules. One can say they were standing firm on "just follow our spec" and ignoring what was practical. A mistake that continued into later XHTML versions.

Anyway, this decision settled the matter for Firefox. It was 7 years before Chrome was born; there were no other significant browser. Thus it was decided.

Specifying the doctype alone does not trigger XML parsing because of following specifications.

Sergent answered 25/2, 2015 at 12:37 Comment(12)
"Self-closing <script> does not happen in HTML 5 because of backward compatibility." – this isn't really true as no aspect of backward compatibility would be broken, that is, code that has been written would still continue to work in newer browsers that supported a self-closing <script>. The real reason is that <script> would be the only self-closing tag as HTML doesn't define any others. Also, only foreign tags are permitted to be self-closing, as void tags do not have an end tag. See start tags, step 6.Zebrawood
@AndyE When you write self-closing <script>, the major browsers at that time do not think it is closed, and will parse the subsequence html as javascript, causing valid HTML5 to break on these old browsers. Thus the proposal is rejected. This is explained in the linked HTML5 mailing list.Sergent
it's unclear as to the main reason the proposal was rejected as the discussion ends pretty abruptly, although breaking existing browsers with new code was one of the issues raised. I'm just pointing out that <script> would be unique as a HTML5 element that is permitted to be self-closing. What I meant in my first comment was that backwards compatibility is not harmed, because backwards compatibility refers to old code running in newer browsers – which is fine in this instance.Zebrawood
@AndyE: What you are describing is forward compatibility - the ability of old code to work with new compiler/interpreter/parser. Backward compatibility is the ability of new code to work with old compiler/interpreter/parser. So yes, backward compatibility was the issue as otherwise pages written with the new spec in mind would not work in old browsers (and yes, it's a tradition of web programming to try and make new code work in old browsers as much as possible).Tsang
HERESY! link rel can work without self closing and self closing, but script can't. This is a matter of changing one line of DOCTYPE. Besides I as a person whose opinion does not matter, declare XHTML doctypes obsolete because html5 tags do not validate to valid xhtml. XHTML is still a fantastic tool, it allows you to create custom entities in an html page allowing you to use entities instead of full link urls, and entities instead of things that may be changed, such as names. But there is no reason to use XHTML doctype for this, it's outdated and never updated. Why is this still an issue!Silsbye
@Dmitry The reality is, disallowing self-closed script is a one way street. As linked, self-closed <script> will break all browsers, users will simply see blank page - game consoles, Internet TV, the IE 11 on the new corporate Win7 PC, millions of Java runtime, or billions of smartphones. Can you upgrade most WebView of most languages on most devices? If HTML5 tried that they would have failed like XHTML2.Sergent
@Sergent Starting a deprecation period and bundling it with a "major compatibility update" would be a start. Alternatively this can be made only to impact xhtml webpages, this way well formed webpages can display both, while traditional html would only accept as it accepts now. While XHTML failed in many areas, it can still push forward to improve writing webpages for devices that are not stuck to one and only one way to write for. Without it, HTML is turning into an assembly, and a heavy one. -continued-Silsbye
@Sergent HTML is already mostly seen as an assembly of the web, as writing in it directly is messy and difficult to maintain. It may as well be replaced with a raw-binary format to save even more space. XHTML leverages much of these issues using patterns, extendable entities, so on that allow maintainable way to write HTML. Instead most sites I see are basically generated, and those that aren't have to struggle with the legacy gotchas like this, and the difficulty of keeping source code agree with 80 character per line limit without making code look messy.Silsbye
@Dmitry This Q&A focus on the why, and may not be a proper place to discuss whether this gotcha make HTML5 obsolete, your dream of wasm for html, or why we should/should not limit our code to 80 characters (which I don't; and I develop these html "generators" as my job).Sergent
@Sergent Sorry, I didn't mean to appear to say any of these things. I don't think HTML5 is obsolete; I don't dream of wasm, i'm merely mentioning the difficulties in writing beautiful hand-made HTML; and i'm quite interested in HTML generation. You're right it's not a thread on how to overcome inconsistencies in HTML, they might be too deep rooted to solve by changing the standard alone.Silsbye
very underrated answerTeamster
A bit of correction: tags that appear to work as self-closed in HTML are not ones with optional end tags, but ones with prohibited end tags (empty, or void, tags). Tags with optional end tags, like <p> or <li>, can't be 'self-closed' since they can have content, so code like <p/> is nothing more that a (malformed) start tag and the content after it, if it is allowed in this element, would end up inside it.Nobles
E
179

In case anyone's curious, the ultimate reason is that HTML was originally a dialect of SGML, which is XML's weird older brother. In SGML-land, elements can be specified in the DTD as either self-closing (e.g. BR, HR, INPUT), implicitly closeable (e.g. P, LI, TD), or explicitly closeable (e.g. TABLE, DIV, SCRIPT). XML, of course, has no concept of this.

The tag-soup parsers used by modern browsers evolved out of this legacy, although their parsing model isn't pure SGML anymore. And of course, your carefully-crafted XHTML is being treated as badly-written SGML-inspired tag-soup unless you send it with an XML mime type. This is also why...

<p><div>hello</div></p>

...gets interpreted by the browser as:

<p></p><div>hello</div><p></p>

...which is the recipe for a lovely obscure bug that can throw you into fits as you try to code against the DOM.

Ellita answered 25/7, 2010 at 2:52 Comment(8)
I'm curious. why does the browser choose to interpret it that way?Halloran
@AhmedAeonAxan: The P element cannot contain DIV elements (this is invalid HTML), so the browser implicitly closes the P element (defined as "implicitly closeable") before the opening DIV tag. However, browsers do tend to behave differently in this respect (as they can do with any invalid HTML).Shoshana
@w3d Is tag soup like that something we can thank Netscape or IE for?Quartz
@ColeJohnson No, this is not tag soup; greim is muddling the border between valid and invalid HTML. Tag soup is what you get when authors don't care for the rules, because browsers use error correction. A missing </p> end tag on the other hand is actually part of the definition of HTML!Elburr
@MrLister - Sort of. "Tag soup" describes how HTML is parsed, not how it's authored. It was a term used to describe disparate strategies browsers used to make sense of HTML, and stands in contrast to strict XML parsing. XML parsing is only allowed for XML mime types, but since those never achieved widespread use, browsers fell back to various "tag soup" schemes, even for otherwise valid documents.Ellita
HTML5 actually standardized the parsing of 'tag soup', including a consistent way to handle invalid markup. Until then, browsers sort of had to figure out what to do with invalid markup on their own, causing inconsistencies. The HTML parser in current browsers is one of the most advanced pieces of software ever written. Blazingly fast and can deal with most any input, producing consistent results.Threecolor
They should not permitted tag soup to begin with and toss out an error to fix the layout instead of trying to figure out what to do with it.Shew
@Dragas—such a browser would have quickly been discarded by most who used it because the web was full of less than perfect markup both human and machine generated. The whole point of HTML was to be easy to author, in response browsers were very forgiving of malformed markup. XHTML was an attempt to make HTML strict. A technical success, but practical failure. :-)Nearsighted
P
44

Internet Explorer 8 and earlier do not support XHTML parsing. Even if you use an XML declaration and/or an XHTML doctype, old IE still parse the document as plain HTML. And in plain HTML, the self-closing syntax is not supported. The trailing slash is just ignored, you have to use an explicit closing tag.

Even browsers with support for XHTML parsing, such as IE 9 and later, will still parse the document as HTML unless you serve the document with a XML content type. But in that case old IE will not display the document at all!

Penman answered 16/9, 2008 at 8:0 Comment(3)
"IE does not support XHTML parsing." was true for IE versions at the time this was written, but is no longer true.Luxurious
@Luxurious can you clarify which version of IE fixed this? (and any specific conditions - e.g. valid doctype required)Coryden
@Coryden IE9 was the first version with full support for XHTML. blogs.msdn.com/b/ie/archive/2010/11/01/…Luxurious
V
29

The people above have already pretty much explained the issue, but one thing that might make things clear is that, though people use <br/> and such all the time in HTML documents, any / in such a position is basically ignored, and only used when trying to make something both parseable as XML and HTML. Try <p/>foo</p>, for example, and you get a regular paragraph.

Vaden answered 16/9, 2008 at 13:7 Comment(0)
S
26

The self closing script tag won't work, because the script tag can contain inline code, and HTML is not smart enough to turn on or off that feature based on the presence of an attribute.

On the other hand, HTML does have an excellent tag for including references to outside resources: the <link> tag, and it can be self-closing. It's already used to include stylesheets, RSS and Atom feeds, canonical URIs, and all sorts of other goodies. Why not JavaScript?

If you want the script tag to be self enclosed you can't do that as I said, but there is an alternative, though not a smart one. You can use the self closing link tag and link to your JavaScript by giving it a type of text/javascript and rel as script, something like below:

<link type="text/javascript" rel ="script" href="/path/tp/javascript" />
Scaliger answered 27/10, 2012 at 9:35 Comment(3)
I like that, why isn't it "smart", though?Should
Because there is a predefined script tag to perform exactly the job of loading a script.. Why would you confuse matters using something else? A hammer hammers in nails.. Would it be smart to use a shoe?Amah
@daveL - And we have <style> tags, yet use link tags for external CSS files. Definition of link tag: "The <link> tag defines a link between a document and an external resource." Seems perfectly logical that the link tag would be used for external CSS or JS...that is what it's for...linking in external files. note I'm not talking spec/cross-browserness/etc, I'm just commenting on the logical nature of using link tags for bringing in both CSS and JS...it actually would make a lot of sense if it were that way. Not sure the shoe [analogy] fits.Bottrop
G
24

Unlike XML and XHTML, HTML has no knowledge of the self-closing syntax. Browsers that interpret XHTML as HTML don't know that the / character indicates that the tag should be self-closing; instead they interpret it like an empty attribute and the parser still thinks the tag is 'open'.

Just as <script defer> is treated as <script defer="defer">, <script /> is treated as <script /="/">.

Groats answered 16/9, 2008 at 7:10 Comment(3)
Elegant as this explanation is, it is in fact wrong. If it were true, there would be a "/" attribute for the script element in the DOM. I've checked IE, Firefox and Opera, and none of them actually contain such an attribute.Cyclo
/ is not a valid attribute name character, so it's discarded. Otherwise this explanation is pretty clear.Av
Actually, some HTML parsers (and especially validators) may interpret the / as a part of the NET (Null End Tag) construction.Loach
N
19

Internet Explorer 8 and older don't support the proper MIME type for XHTML, application/xhtml+xml. If you're serving XHTML as text/html, which you have to for these older versions of Internet Explorer to do anything, it will be interpreted as HTML 4.01. You can only use the short syntax with any element that permits the closing tag to be omitted. See the HTML 4.01 Specification.

The XML 'short form' is interpreted as an attribute named /, which (because there is no equals sign) is interpreted as having an implicit value of "/". This is strictly wrong in HTML 4.01 - undeclared attributes are not permitted - but browsers will ignore it.

IE9 and later support XHTML 5 served with application/xhtml+xml.

Necessary answered 16/9, 2008 at 12:48 Comment(1)
IE 9 supports XHTML and IE is no longer >51%. Could you update your answer?Walkyrie
U
6

That's because SCRIPT TAG is not a VOID ELEMENT.

In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all!

In xhtml, everything is Generic, therefore they all need termination e.g. a "closing tag"; Including br, a simple line-break, as <br></br> or its shorthand <br />.

However, a Script Element is never a void or a parametric Element, because script tag before anything else, is a Browser Instruction, not a Data Description declaration.

Principally, a Semantic Termination Instruction e.g., a "closing tag" is only needed for processing instructions who's semantics cannot be terminated by a succeeding tag. For instance:

<H1> semantics cannot be terminated by a following <P> because it doesn't carry enough of its own semantics to override and therefore terminate the previous H1 instruction set. Although it will be able to break the stream into a new paragraph line, it is not "strong enough" to override the present font size & style line-height pouring down the stream, i.e leaking from H1 (because P doesn't have it).

This is how and why the "/" (termination) signalling has been invented.

A generic no-description termination Tag like < />, would have sufficed for any single fall off the encountered cascade, e.g.: <H1>Title< /> but that's not always the case, because we also want to be capable of "nesting", multiple intermediary tagging of the Stream: split into torrents before wrapping / falling onto another cascade. As a consequence a generic terminator such as < /> would not be able to determine the target of a property to terminate. For example: <b>bold <i>bold-italic < /> italic </>normal. Would undoubtedly fail to get our intention right and would most probably interpret it as bold bold-itallic bold normal.

This is how the notion of a wrapper ie., container was born. (These notions are so similar that it is impossible to discern and sometimes the same element may have both. <H1> is both wrapper and container at the same time. Whereas <B> only a semantic wrapper). We'll need a plain, no semantics container. And of course the invention of a DIV Element came by.

The DIV element is actually a 2BR-Container. Of course the coming of CSS made the whole situation weirder than it would otherwise have been and caused a great confusion with many great consequences - indirectly!

Because with CSS you could easily override the native pre&after BR behavior of a newly invented DIV, it is often referred to, as a "do nothing container". Which is, naturally wrong! DIVs are block elements and will natively break the line of the stream both before and after the end signalling. Soon the WEB started suffering from page DIV-itis. Most of them still are.

The coming of CSS with its capability to fully override and completely redefine the native behavior of any HTML Tag, somehow managed to confuse and blur the whole meaning of HTML existence...

Suddenly all HTML tags appeared as if obsolete, they were defaced, stripped of all their original meaning, identity and purpose. Somehow you'd gain the impression that they're no longer needed. Saying: A single container-wrapper tag would suffice for all the data presentation. Just add the required attributes. Why not have meaningful tags instead; Invent tag names as you go and let the CSS bother with the rest.

This is how xhtml was born and of course the great blunt, paid so dearly by new comers and a distorted vision of what is what, and what's the damn purpose of it all. W3C went from World Wide Web to What Went Wrong, Comrades?!!

The purpose of HTML is to stream meaningful data to the human recipient.

To deliver Information.

The formal part is there to only assist the clarity of information delivery. xhtml doesn't give the slightest consideration to the information. - To it, the information is absolutely irrelevant.

The most important thing in the matter is to know and be able to understand that xhtml is not just a version of some extended HTML, xhtml is a completely different beast; grounds up; and therefore it is wise to keep them separate.

Unstoppable answered 17/8, 2017 at 22:54 Comment(1)
I thought the purpose of HTML was to stream data to an agent (usually a browser), hot a human being.Flavio
C
4

Difference between 'true XHTML', 'faux XHTML' and 'ordinary HTML' as well as importance of the server-sent MIME type had been already described here well.

If you want to try it out right now, here is simple editable snippet with live preview including self-closed script tag (see <script src="data:text/javascript,/*functionality*/" />) and XML entity (unrelated, see &x;).

As you can see, depending on the MIME type of embedding document the data-URI JavaScript functionality is either executed and consecutive text displayed (in application/xhtml+xml mode) or not executed and consecutive text 'devoured' by the script (in text/html mode).

div { display: flex; }
div + div {flex-direction: column; }
<div>Mime type: <label><input type="radio" onchange="t.onkeyup()" id="x" checked  name="mime"> application/xhtml+xml</label>
<label><input type="radio" onchange="t.onkeyup()" name="mime"> text/html</label></div>
<div><textarea id="t" rows="4" 
onkeyup="i.src='data:'+(x.checked?'application/xhtml+xml':'text/html')+','+encodeURIComponent(t.value)"
><?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
[<!ENTITY x "true XHTML">]>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
  <p>
    <span id="greet" swapto="Hello">Hell, NO :(</span> &x;.
    <script src="data:text/javascript,(g=document.getElementById('greet')).innerText=g.getAttribute('swapto')" />
    Nice to meet you!
    <!-- 
      Previous text node and all further content falls into SCRIPT element content in text/html mode, so is not rendered. Because no end script tag is found, no script runs in text/html
    -->
  </p>
</body>
</html></textarea>

<iframe id="i" height="80"></iframe>

<script>t.onkeyup()</script>
</div>

You should see Hello, true XHTML. Nice to meet you! below textarea.

For incapable browsers you can copy content of the textarea and save it as a file with .xhtml (or .xht) extension (thanks Alek for this hint).

Cost answered 22/11, 2017 at 0:25 Comment(0)
I
4

Simply modern answer is because the tag is denoted as mandatory that way

Tag omission None, both the starting and ending tag are mandatory.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

Imprest answered 10/11, 2019 at 14:38 Comment(1)
Doesn't make sense if a src attribute is given. But I guess it makes HTML easier to parse.Flavio

© 2022 - 2024 — McMap. All rights reserved.