javascript tutorial - [5 Solutions] self-closing script tags - javascript - java script - javascript array



Problem :

Why don't self-closing script tags work?

Solution 1:

<script src="foobar.js" /> <!-- self-closing script tag -->
click below button to copy the code. By JavaScript tutorial team

Only this is recognized:

<script src="foobar.js"></script>
click below button to copy the code. By JavaScript tutorial team

Solution 2:

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/>).

Solution 3:

'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.

Solution 4:

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, tags 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 tag-soup/SGML unless you send it with an XML mime type. This is also why...

<p><div>hello</div></p>
click below button to copy the code. By JavaScript tutorial team

...gets interpreted by the browser as:

<p></p><div>hello</div><p></p>
click below button to copy the code. By JavaScript tutorial team

Solution 5:

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!


Related Searches to javascript tutorial - self-closing script tags