What I liked at first about @Orangepips's answer over @Anooj's is the ease of future maintenance over requiring a separate Javascript block every time you included the <script> in your CFMs.
After a few minutes of thinking about it, however, this is easily eliminated by combining the two answers. This gives you modularity for ease of today's development and future maintenance that you seek -- PLUS as a best practice gives you isolation & caching of the static Javascript in order to decrease your CF page request size & response speed.
Basically you should create a CF-based facade that you will include or call every time you want the Javascript functionality. In my example, I made the facade a callable function that you can pass the JS params into (as @Orangepips was alluding to) in order to tightly control what vars get passed to the JS.
(As an aside, as a best practice, I tend to put all inline JS into variable then stuff it into CFHEADER, to assure it's in the page header.)
dosomething.js
<script type='text/javascript'>
<!-- assert vars were passed in -->
if ( source == undefined )
alert("Developer error: source not defined.");
return;
}
if ( urlpath == undefined )
alert("Developer error: urlpath not defined.");
return;
}
<!-- do some js stuff --->
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">
<!-- var init -->
<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 in having the code separated out (JS is separate from JS-var defining facade is separate from individual views calling it). E.g. in adding a variable, you could make it backwards compatible so all existing views continue to work.
udf.cfm changes:
<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