Updating a JavaScript to be XHTML compliant
by
, 04-02-2009 at 05:16 AM (50303 Views)
As a webmaster you've undoubtedly noticed the increasing shift in coding practices from HTML to XHTML on the web. If you're a professional web designer, you've probably even heard it first hand from your clients who demand their web pages be XHTML compliant. I get quite a lot of emails on a monthly basis asking for help in making a webpage that contains a DHTML script to be XHTML compliant. A common misconception is that this is a difficult process, which can be no further from the truth.
There are two ways to go about making a DHTML or JavaScript XHTML compliant, both should take no more than a few moments of your time.
Method 1: For inline JavaScript, wrap the code itself in the CDATA tag coupled with some clever use of JavaScript comments to let the validator know the content within the script should not be parsed for XHTML validity:
As you can see, just wrap any inline JavaScript with the parts in red, and you're done. You may also choose to use an alternate version of the CDATA/ JavaScript comment code:Code:<script type="text/javascript"> /*<![CDATA[*/ //The JavaScript code itself //The JavaScript code itself // etc... /*]]>*/ </script>
Either code wrappers work.Code:<script type="text/javascript"> //<![CDATA[ //The JavaScript code itself //The JavaScript code itself // etc... //]]> </script>
Method 2: The other method for making your JavaScript XHTML compliant is to remove the entire script from your page, and place its contents inside an external JavaScript file, then reference this file on your page:
Where "myscript.js" contains the script itself minus the surrounding SCRIPT tags. Comments within the script tags are still allowed.Code:<script type="text/javascript" src="myscript.js"> //Comment here //Comment here </script>
And there you have it. Now a JavaScript no longer has to trip up the XHTML validity of your pages!