27

I'd like to include a javascript file on every page of a site. I can do this with:

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

This works fine - however as there's nothing between the two tags, I wanted to change it to:

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

If I do this, it doesn't work - nothing after that line loads on the page.

Any ideas why? Thanks

4

3 Answers 3

33

Unfortunately, the HTML specs for REQUIRE a closing tag...

HTML Standard, section 18.2.1

18.2.1 The SCRIPT element

Start tag: required, End tag: required

Sign up to request clarification or add additional context in comments.

Comments

3

This is not a bug, it's standard behavior.

Also, empty HTML elements are often not rendered:

<div style="background:red"></div> displays, <div style="background:red" /> doesn't

1 Comment

This element IS rendered but not visible, since it's size is zero pixel height and width
2

HTML doesn't support self closing tags. If you want to use them you need to use an xml based doctype AND serve the file as xml.

XHTML or the xml serialisation of html5 would both work.

Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>XHTML5 Template</title>
    <meta charset="utf-8" />
    <script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js" />
  </head>
  <body>
  </body>
</html>

Save this in a file with a .xhtml extension and open it in a modern browser and the self closing tag will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.