Freddie
Freddie

Reputation: 1707

Include JavaScript file in HTML won't work as <script .... />

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

Upvotes: 27

Views: 77082

Answers (3)

david
david

Reputation: 18258

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.

Upvotes: 2

Dekker500
Dekker500

Reputation: 821

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

Upvotes: 33

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

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

Upvotes: 3

Related Questions