- Including Valid External Javascript in XHTML
- Including external Javascript by using the DOM
- Including external JS via a javascript writeln();
- Including Valid Inline Javascript in XHTML – CDATA & comments
- Include valid Javascript eventhandlers in your XHTML
Including Valid External Javascript in XHTML
Correct way to include an external javascript file:
<script src="filename.js" type="text/javascript"></script> <script src="filename.js" type="text/javascript" charset="utf-8"></script>
- Even when
src
is specified, the script tag is not an empty tag, and cannot be written<script src=".... />
. If you include thesrc
you should not include any script before the opening and closing tags as browser handling of any script between the tags is not reliable. - By convention, the external javascript file should have a
.js
extension, but this is not required. - In XHTML, the
type
attribute is a required attribute. - The
language
attribute should only be included if the language is not javascript. The browser automatically defaults to the latest version of javascript it supports, so only specify the script language if the languge is something other than the lastest version of javascript. So, includelanguage="vb"
if you are including a visual basic script, but don’t includelanguage="javascript1.3"
if you are including a javascript file. - The
charset
attribute is optional. Included it (charset="utf-8"
) if your script includes atypical characters. Omit it if you use only keyboard characters or if you escape your Javascript entity characters.. - Although you will usually find the
script
tag inhead
area, the best place to put it is right before the end of thebody
. The reason? When the browser encounters a script during page load it ceases downloading from the server. A<script src="url></script> will prevent the download of other page components until the
.js
file has been retrieved, compiled and executed. Placing the.js
at the end of thebody
can improve both perceived and actual download time. However, if rendering the page requires functions from the javascript, include the javascript before the page calls required functions. - The
defer
attribute – writtendefer="defer"
in XHTML – is a fairly useless attribute of thescript
tag. It tells the browser that the script does not create any content allowing the browser to defer interpreting the script. The delaying of execution of scripts until after the body content is parsed and rendered is optional for the browser, and the browser still downloads the script, putting download of all other elements on hold, so unless there is a reason to include the script earlier in the page, the recommendation is to place the external script call immediately before the</body>
. runat="server"
is an optional attribute/value. I haven’t ever used it, so can’t really comment on it. I assume it’s used for non-javascript scripts and for ASP.net javascripts, telling the server to run the script, or, in the case of any element in ASP.net, on the server.
Including external Javascript by using the DOM
The following onload function appends a javascript file (the source in this case is ‘myjsfile.js’) to your HTML document.
window.onload=function(){ if(!document.getElementById || !document.createElement){return;} var newjs=document.createElement('script'); newjs.type='text/javascript'; newjs.src='myjsfile.js'; document.getElementsByTagName('head')[0].appendChild(newjs); }
or you can also dynamically add a script to the DOM via a function call:
// loadscript('filepath/myjsfile.js'); function loadScript(src) { newjs= document.createElement( "script" ); newjs.src = src; newjs.type='text/javascript'; head = document.getElementsByTagName( "head" )[0]; head.appendChild(newjs); }
Explanation
- The first line test to see if you browser is ancient and doesn’t accept Javascript
- The second line creates the the object, but doesn’t add it to the page. The third and fourth lines add properties to our newly created object.
- The Javascript file only gets added in the last line. We used the DOM to find the parent element for where we want our Javascript file added, and then appended the javascript file object as a child element of the targeted parent element.
Including javascript via a javascript writeln();
I will eventually write the specifics as to why. In the meantime, if you are going to include script within a script by using writeln()
— either including a block of code or including an external javascript file — you have to break the opening and closing script
tag two parts.
document.write("<scr"+"ipt type=\"text/javascript\" src=\"yoursource.js\"></scr"+"ipt>");
Including Valid Inline Javascript in XHTML
You may notice that your XHTML does not validate because of code in your javascript. Here is the correct way to include an internal javascript file:
<script type="text/javascript">
//<![CDATA[
code here
//]]>
</script>
- In XHTML, the
type
attribute is a required attribute. - Do not include the
language
attribute, unless you’re including something other than javascript. - CDATA is required in XHTML because using the characters
<, >, &
and"
as characters rather than entities will not validate, and Javascript would not understand it if you coded something asif (A > B){}
- The old fashioned method of hiding the script from browsers of commenting out the javascript, seen on most websites, is useless today as all browsers understand the script tag. All browsers either support javascript or are smart enough to ignore the content between the script tag if they don’t support javascript:
<script type="text/javascript"> <!-- Hiding this way is no longer necessary //--> </script>
- However, not all browsers support XHTML and therefore may not understand
<![CDATA[
, so hiding the]]>
CDATA
from non-XHTML browsers with the single line javascript comment of//
, allowes XHTML compliant browsers to except special characters within theCDATA
, and non-compliant browsers simply ignore theCDATA
call since it’s part of a comment. - The best place to put it is right before the end of the
body
unless rendering the page requires functions from the javascript.
Include valid Javascript eventhandlers in your XHTML
<a href="somevaliddestination.html" onclick="someaction();">
Note: I am working on an entry for adding event handlers/listeners with javascript, which is preferable to inline onclick="someaction();"
. When done, I will replace this paragraph with a link to that entry.
- Eventhandlers can be added as attributes to XHTML elements. Like all attributes, the eventhandler should be lowercase. The value, however, is likely case sensitive so case matters, but lowercase is not a requirement.
- Let links be links. If you are placing an event handler in a link, make sure there is a valid destination for the link.
- If you need to create an event, but don’t have a valid link destination, then put your event handler in a non-link element such as
<span onmouseover="someaction('parameter');">
. - Like all attribute values, an event handler value should be enclosed in quotes. It is recommended that you use double quotes, since you may need to encapsulate a string in quotes in single quotes within your javascript. Why? You cannot include
<![CDATA[ ]]>
in an event handler, and you can’t have quotes (") in XHTML that are unescaped. If you need to use quotes inline, use \ before a single quote, and use " within a string. \" will not validate. You cannot use " as it will end your attribute value/javascript eventhandler. - Of course, it is best to avoid inline event handlers. Keep your content and your javascript separate: use an external javascript to attach event handlers to your code.
Notes:
- It is best to use external javascript files!
- If you are effecting the DOM during page load, and use innerHTML = “string…” after you do it, Internet Explorer erroneously retroactively-prematurely closes the DOM throwing an "Operation Aborted" error. Either avoid using
innerHMTL
, or don’t modify the DOM until the page is fully loaded (or, better yet, avoid both). See IE and Operation Aborted for more info on this special IE quirk. - See also the W3 speccifications for the
script
in XHTML
Goooood article!
You help so much webmasters that want their XHTML sites validated and well-formed !
Thank you!
Vito
Your description of IE’s closing of the DOM if a script affects it during load as being erroneous is based on an incorrect assumption about Xhtml.
Xhtml is Xml. An Xml ‘file’ isn’t known to be well-formed until it is completely parsed. The Xml DOM can’t really exist until the Xml is completely loaded by the browser. Script shouldn’t execute at all until the DOM is complete, when the html tag is closed.
That a web developer would expect script to execute in an XHTML document before the DOM was completely constructed shows a misunderstanding of what XHTML is. If a developer needs script to execute before the DOM is completely constructed, then the document should use an HTML document type–not XHTML–and depend on legacy browser support.
What you see when it ‘works’ for Xhtml is a fallback behavior of treating XHTML as HTML, which should not be the default behavior if the browser claims support for XHTML.