Monday, February 1, 2010

Nerd: Trouble with Google Maps API, script tag, and jspx

I use jspx in a couple of places for OneBusAway, which is an XML-ified version of the venerable Java Server Pages (jsp) standard. I recently had a mysterious issue where I couldn't get a page to load properly that was referencing a <script> element for loading the Google Maps API. It turned out to be a problem with the way a jspx file is treated as an XML document. In my source file, I had something like this:

<script type=\"text/javascript\" src=\"…\"></script>

However, when that snippet is parsed as XML and spit back out again, it ends up looking like:

<script type=\"text/javascript\" src=\"…\"/>

That's a problem, because the Google Maps API does some script injection in the head of the html document on loading that seems to break if you use <script/> instead of <script></script>. Why? I don't really know. However, it was an issue on Firefox 3.5 that almost drove me insane.

Thankfully, there is a simple hack to fix the issue. Just insert a CDATA section in your own script tag and it won't be collapsed by the XML parser:

<script type=\"text/javascript\" src=\"…\"><![CDATA[<!-- -->]]></script>

Did the trick for me. I post it here so that Google might index it and help out somebody else out there some day.