How can I include an external javascript file that contains coldfusion code?
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.
I would suggest you create a script block prior to the js include which contains all the variables to be used inside the including js file. In your case, move those cfoutput variable you put inside the js file to the main file
<script type='text/javascript'>
var sourceName = <cfoutput>#Application.name#</cfoutput>
</script>
<script src="js/myPage.js" type="text/javascript"/>
In the myPage.js file you can use the variable sourceName which has the actuall value from the coldfusion variable. thus helping you from seperating coldfusion code and js code.
If you have a a lot of variables to be moved out, consider creating object type variable and add all those variable inside it.
NOTE : Adding js with script tag will help it cache and increase page performance. So do not load js file as cfm file
It would be more efficient if you moved the ColdFusion code back to where you got it from, where you would use it to set some JavaScript variables, and leave only pure JavaScript which would then use those variables in your external JavaScript files. This would be the simplest solutions. Something more advanced would be to define functions in your external JavaScript files that would get called from your script tags in your ColdFusion-generated HTML.