At first I liked @Orangepips to answer @Anooj - this is the simplicity of future maintenance, requiring a separate Javascript block every time you include <script> in your CFMs.
After a few minutes of thinking about this, however, this is easily eliminated by combining the two answers. This gives you modularity for the convenience of today's development and the future service you are looking for - PLUS as the best practice gives you isolation and caching of static Javascript to reduce request size and CF response speed.
Basically you have to create a CF-based façade that you will include or invoke every time you want to use Javascript. In my example, I made the facade a function called that you can pass JS parameters to (as @Orangepips pointed out) to precisely control which vars are passed to JS.
(As an aside, as a best practice, I try to put all the embedded JS in a variable and then forward them to CFHEADER to assure it of the page title.)
dosomething.js
<script type='text/javascript'> if ( source == undefined ) alert("Developer error: source not defined."); return; } if ( urlpath == undefined ) alert("Developer error: urlpath not defined."); return; } alert('source: ' + source + ", urlpath: " + urlpath ); </script>
udf.cfm:
<cffunction name="doSomething" output="true" returntype="void"> <cfargument name="source" required="true" /> <cfargument name="urlpath" required="true" /> <cfsavecontent variable="header"> <script type="text/javascript"> <cfoutput> var source = '#arguments.source#'; var urlpath = '#arguments.urlpath#'; </cfoutput> </script> <script language="JavaScript" type="text/javascript" src="dosomething.js"></script> </cfsavecontent> <cfhtmlhead text="#header#"> </cffunction>
application.cfm
<cfinclude template="udf.cfm">
view1.cfm:
<cfoutput>#doSomething("view 1", "http://myurl/view1")#</cfoutput>
view2.cfm:
<cfoutput>#doSomething("view 2", "http://myurl/view2")#</cfoutput>
Any future changes become easier when you disable the code (JS is separate from the JS-var defining the facade, separated from the individual views that invoke it). For example. when you add a variable, you can make it backward compatible so that all existing views continue to work.
udf.cfm:
<cfargument name="newVar" required="false" default="" /> <cfif len(arguments.newVar)> var newVar = "#arguments.newVar#"; </cfif>
dosomething.js changes:
// keep JS backwards compatible if ( newVar != undefined) { // new var was passed in, do something with it } // else, not passed in