Snip
|
Including Valid Inline Javascript in XHTML
|
---|
Categories |
|
---|
For Snip |
loading snip actions ... |
---|---|
For Page |
loading url actions ... |
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>
type
attribute is a required attribute. language
attribute, unless you’re including something other than javascript. <, >, &
and "
as characters rather than entities will not validate, and Javascript would not understand it if you coded something as if (A > B){}
<script type="text/javascript"> <!-- Hiding this way is no longer necessary //--> </script>
<![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 the CDATA
, and non-compliant browsers simply ignore the CDATA
call since it’s part of a comment.
body
unless rendering the page requires functions from the javascript. HTML |
<h3 id="js_o4">Including Valid Inline Javascript in XHTML</h3> <p>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:</p> <pre><code><script type="text/javascript"> //<![CDATA[ code here //]]> </script></code></pre> <ul> <li>In XHTML, the <code>type</code> attribute is a <strong>required</strong> attribute. </li> <li>Do not include the <code>language</code> attribute, unless you’re including something other than javascript. </li> <li>CDATA is required in XHTML because using the characters <code><, >, &</code> and <code>"</code> as characters rather than entities will not validate, and Javascript would not understand it if you coded something as <code>if (A &gt; B){}</code> </li> <li>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: <pre><script type="text/javascript"> <!-- Hiding this way is no longer necessary //--> </script> </pre> </li> <li>However, not all browsers support XHTML and therefore may not understand <code><![CDATA[ </code><p> ]]>, so hiding the <code>CDATA</code> from non-XHTML browsers with the single line javascript comment of <code>//</code>, allowes XHTML compliant browsers to except special characters within the <code>CDATA</code>, and non-compliant browsers simply ignore the <code>CDATA</code> call since it’s part of a comment. </p></li><li>The best place to put it is right before the end of the <code>body</code> unless rendering the page requires functions from the javascript. </li></ul> |
---|