The script element is generally used in two ways, to either contain code between the two tags of the script element or to include code. When it includes code it does not technically need the end tag for the script
element.
The quickest way to test the code as actual XHTML (application/xhtml+xml) is to create a file with a .xhtml file extension and then open that file in Firefox. Gecko, unlike the two Webkit forks (Chrome and Safari) and Trident (IE) will actually break the page and instead show an XML parsing error message, other rendering engines will simply stop rendering at the point the XML parse error was encountered.
A few things about correctly handling script
elements...
- There is no such mime as "text/javascript", it's actually
application/javascript
.
- Microsoft's IE doesn't understand JavaScript until IE9 and will simply not render JavaScript unless it's served with this non-existent weird mime "text/javascript". If you're building your own stuff 2014 or onwards simply ignore Internet Explorer 8 and older as their shares will be utterly negligible by the time you bring something to market.
- Avoid putting script elements in the body element if you're trying to learn how to code clean and strict, it'll force you to organize things; ensure you use the
defer="defer"
attribute/value pair if you had been putting script
elements in the body for performance reasons.
- If you have a lot of scripts simply use a server scripting language like PHP to
include()
multiple files in a single file. You'll have to use Apache to enable PHP rendering in a *.js
file and then you'll need to output the correct mime.
JavaScript Example
<script defer="defer" type="application/javascript">
//<![CDATA[
window.onload = function
{
alert('Hello World.');
}
// ]]>
</script>
Everything that I've mentioned can be seen at my website in my profile as I code as strictly as possible. Sure strict code takes longer though I end up with almost utterly no maintenance which saves me hordes of time in the long run.