So I have this code:
<!doctype html>
<html lang="en">
<head>
<title>Example</title>
<link type="text/css" rel="stylesheet" href="tjg.css"/>
</head>
<body>
<script type="text/javascript" src="tjg.js"/>
<p>This paragraph is an example.</p>
</body>
</html>
And the Javascript file (tjg.js) is empty. But when I view it in all of my browsers. It just shows nothing, not the example paragraph. This only happens when the:
<script type="text/javascript" src="tjg.js"/>
is in my code. If it isn't (head/body, doesn't matter) than it will work fine. How can I fix this?
So I have this code:
<!doctype html>
<html lang="en">
<head>
<title>Example</title>
<link type="text/css" rel="stylesheet" href="tjg.css"/>
</head>
<body>
<script type="text/javascript" src="tjg.js"/>
<p>This paragraph is an example.</p>
</body>
</html>
And the Javascript file (tjg.js) is empty. But when I view it in all of my browsers. It just shows nothing, not the example paragraph. This only happens when the:
<script type="text/javascript" src="tjg.js"/>
is in my code. If it isn't (head/body, doesn't matter) than it will work fine. How can I fix this?
Use
<script type="text/javascript" src="tjg.js"></script>
The />
notation doesn't work in HTML as you expect.
The script tag cannot be self closed.
Do this instead:
<script type="text/javascript" src="tjg.js"></script>
Also you could set your javascript tag in the <head>
section instead of the body
tag
<head>
<title>Example</title>
<link type="text/css" rel="stylesheet" href="tjg.css"/>
<script type="text/javascript" src="tjg.js"></script>
</head>
Yes, it does have an effect, since browsers interpret the tag
<script type="text/javascript" src="tjg.js"/>
as if the slash before “>” was not there, i.e. as simply a start tag. Everything after it will be parsed as content of that element, up to the next </script>
end tag or end of data, whichever es first. In the sample case, the rest of the document is parsed that way and ignored (browsers won’t even try to process it as a script, since the element does not end).
So you really need to use a </script>
end tag, even if the script
element content is meant to be empty, as suggested in other answers.
This applies to actual browser behavior when using HTML parser. Formally, by SGML rules, the situation is a bit different, but this only matters in formal SGML validation (e.g., when using http://validator.w3).
When the data is served as “genuine XHTML”, with an XML content type, things are different. Self-closing actually works. But the sample code does not work when served that way: the string doctype
must be in uppercase in XHTML, and the html
element must have the attribute xmlns="http://www.w3/1999/xhtml"
. There is normally no point in serving XHTML that way on the Web. So this point is really theoretical, but it has the point: it illustrates that “self-closing tags” actually work in a very limited environment only.