How can I include an external javascript file that contains coldfusion code?

froadie picture froadie · Feb 28, 2011 · Viewed 8.9k times · Source

I have a few coldfusion files that use the same exact javascript code. I want to separate the javascript out into a .js file and include it in each of the files so that I don't have to repeat everything several times. So, I separated the javascript code into a file named "myPage.js", and in "myPage.cfm" I included a script tag -

<script language="javascript" src="myPage.js"></script>

The problem is that there's some coldfusion code spread among the javascript that injects values using <cfoutput>s and such, and that is no longer being translated correctly, probably because it's trying to read it as pure javascript. Is there any way I can have an external js file but indicate that I want it to use coldfusion to interpret it as well?

One workaround that I've found is to put the javascript into a coldfusion file instead of a javascript file, called "myPageJavascript.cfm", surround all the javascript code in a <script type="text/javascript"> tag, and then use a cfinclude to include that javascript in all the pages. This works fine, but it doesn't seem to me as intuitive as including a js file... What's the standard practice for situations like this? Is there any way to implement this as an external js file, or should I just stick to my coldfusion template file?

Answer

orangepips picture orangepips · Feb 28, 2011

Other answers are more elegant and efficient, but the easy way out is change the file extension from .js to .cfm as such:

<script language="javascript" src="myPage.cfm?id=#createUuid()#"></script>

The createUuid() is there to prevent caching, assuming file output will differ, most likely based on variables from the session scope. The client loads this as JavaScript, while the server processes it as ColdFusion. You can do the same thing with style sheets as well.

Now, if your JavaScript depends on values from the calling page you can pass them along on the URL:

<script language="javascript" src="myPage.cfm?name1=value1&name2=value2"></script>

In this situation you can actually can take advantage of caching when the same URL parameters are passed.

Overall, this approach can be a lot less effort than refactoring code to keep the .js file "pure", while outputting variables it depends upon in a <script/> block beforehand.