Today I came across the need to serve up a dynamic javascript include. What does that mean? It means that I had this code in place:
<script language="JavaScript" src="CustomWrappers.js"></script>
And I wanted
CustomWrappers.js to return different content based on some query string parameters I would pass in.
First, as a quick proof of concept, I simply copied the contents of
CustomWrappers.js into a new file I created called
CustomWrappers.cfm, and changed the
src attribute of my
script tag to use this new file.
<script language="javascript" src="CustomWrappers.cfm"></script>
Eventually, I want to be able to do this:
<script language="javascript" src="CustomWrappers.cfm?myVar=#myVal#&myVar2=#myVal2#"></script>
Unfortunately, that did not work – IIS served the template content as text/html, rather than text/plain; which we can't complain about, because that's what it should do when you request a CFM template. I tried adding this line to the top of the template:
<cfcontent type="text/plain">
Later, when I was discussing this issue with
Ray Camden, he said this should be all I have to do. And I probably would have agreed with him immediately, if I hadn't already seen it not work. As it turns out, this is a perfectly valid solution – but the reason it wouldn't work for me is that my development environment runs the Developer Edition of MX7, and with debugging enabled; so what is returned when the browser requests that file is:
<META NAME="ColdFusionMXEdition" CONTENT="ColdFusion DevNet Edition – Not for Production Use.">
[my javascript content]
</td></td></td></th></th></th></tr></tr>………………
And so on, with the debug output; which is obviously not valid JavaScript syntax. Unfortunately, the Meta tag will cause issue with the JavaScript, so using
&lt;cfsetting showDebugOutput="false"&gt; won't totally resolve the issue. In order to get around this annoyance, I used the following code:
<cfsavecontent variable="theJS">
[my javascript content]
</cfsavecontent>
<cfcontent type="text/plain" variable="#CharsetDecode(theJS, 'utf-8')#">
This definitely takes more time to process, but resolved the issue of serving dynamic JS includes with CF in developer mode and debugging enabled.