简体   繁体   English

如何包含包含coldfusion代码的外部javascript文件?

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

I have a few coldfusion files that use the same exact javascript code. 我有一些使用相同的javascript代码的coldfusion文件。 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. 我想将javascript分成一个.js文件并将其包含在每个文件中,这样我就不必多次重复所有内容。 So, I separated the javascript code into a file named "myPage.js", and in "myPage.cfm" I included a script tag - 所以,我将javascript代码分成了一个名为“myPage.js”的文件,而在“myPage.cfm”中我添加了一个脚本标记 -

<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. 问题是,在使用<cfoutput>等注入值的javascript中有一些coldfusion代码传播,并且不再正确翻译,可能是因为它试图将其作为纯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? 有没有办法我可以有一个外部的js文件,但表明我希望它使用coldfusion来解释它?

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. 我找到的一个解决方法是将javascript放入coldfusion文件而不是javascript文件,称为“myPageJavascript.cfm”,将<script type="text/javascript">标记中的所有javascript代码包围,然后使用cfinclude在所有页面中包含该javascript。 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? 这样可以正常工作,但在我看来并不像包含js文件一样直观......对于这样的情况,标准做法是什么? Is there any way to implement this as an external js file, or should I just stick to my coldfusion template file? 有没有办法将其作为外部js文件实现,还是应该坚持我的coldfusion模板文件?

Other answers are more elegant and efficient, but the easy way out is change the file extension from .js to .cfm as such: 其他答案更优雅,更有效,但简单的方法是将文件扩展名从.js更改为.cfm ,如下所示:

<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. createUuid()用于防止缓存,假设文件输出不同,很可能基于session范围中的变量。 The client loads this as JavaScript, while the server processes it as ColdFusion. 客户端将其加载为JavaScript,而服务器将其作为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: 现在,如果您的JavaScript依赖于来自调用页面的值,您可以在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. 在这种情况下,当传递相同的URL参数时,您实际上可以利用缓存。

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. 总的来说,这种方法比重构代码以保持.js文件“纯粹”要少得多,同时输出预先依赖于<script/>块的变量。

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. 我建议你在js include之前创建一个脚本块,其中包含要在js文件中使用的所有变量。 In your case, move those cfoutput variable you put inside the js file to the main file 在您的情况下,将放在js文件中的cfoutput变量移动到主文件中

    <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. 在myPage.js文件中,您可以使用变量sourceName,它具有来自coldfusion变量的实际值。 thus helping you from seperating coldfusion code and js code. 从而帮助您分离coldfusion代码和js代码。

If you have aa 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. 注意:使用脚本标记添加js将有助于缓存并提高页面性能。 So do not load js file as cfm file 所以不要将js文件加载为cfm文件

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. 如果您将ColdFusion代码移回到您从中获取它的位置,您将使用它来设置一些JavaScript变量,并且只留下纯JavaScript然后在外部JavaScript文件中使用这些变量,那么效率会更高。 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. 更高级的是在外部JavaScript文件中定义函数,这些函数将从ColdFusion生成的HTML中的脚本标记中调用。

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. 我最初喜欢@ Orangepips对@ Anooj的回答是,每次在CFM中包含<script> ,都需要单独的Javascript块,以便于日后维护。

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. 这为您提供了模块化,便于您今天的开发和未来的维护 - PLUS作为一种最佳实践,可以隔离和缓存静态Javascript,以降低您的CF页面请求大小和响应速度。

Basically you should create a CF-based facade that you will include or call every time you want the Javascript functionality. 基本上,您应该创建一个基于CF的外观,您将在每次需要Javascript功能时包含或调用它。 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. 在我的例子中,我使Facade成为一个可调用的函数,你可以将JS参数传递给(如@Orangepips所暗示的那样),以便严格控制传递给JS的vars。

(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.) (顺便说一句,作为一种最佳实践,我倾向于将所有内联JS放入变量中,然后将其填充到CFHEADER中,以确保它位于页眉中。)

dosomething.js 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: 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 application.cfm

<cfinclude template="udf.cfm">

view1.cfm: view1.cfm:

<cfoutput>#doSomething("view 1", "http://myurl/view1")#</cfoutput>

view2.cfm: 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). 将代码分离出来后,任何未来的更改都会变得更加容易(JS与JS-var定义的外观分离,与调用它的各个视图是分开的)。 Eg in adding a variable, you could make it backwards compatible so all existing views continue to work. 例如,在添加变量时,您可以使其向后兼容,以便所有现有视图继续工作。

udf.cfm changes: udf.cfm更改:

<cfargument name="newVar" required="false" default="" /> 
<cfif len(arguments.newVar)>
var newVar = "#arguments.newVar#";
</cfif>

dosomething.js changes: dosomething.js更改:

// keep JS backwards compatible
if ( newVar != undefined) {
    // new var was passed in, do something with it
}
// else, not passed in 

To identify what came from the server, and to have the CF function toScript render the variables correctly, including structs and arrays, I use this method: 要识别来自服务器的内容,并使CF函数toScript正确呈现变量,包括结构和数组,我使用此方法:

<script>
    var cf = {};
    <cfscript>
        writeOutput(toScript(application.applicationname,'cf.app'));
        writeOutput(toScript(cgi.remote_addr,'cf.url'));
    </cfscript>
</script>

renders to: 呈现给:

<script>
    var cf = {};
    cf.app="Lucee";cf.url="149.79.80.135";
</script>

and now in your external .js you just use cf.app, cf.url ... and so on. 现在在你的外部.js你只需使用cf.app,cf.url ......等等。

It can be very convenient sometimes to pass along the URL struct on a get or FORM struct on a post. 有时在帖子上的get或FORM结构上传递URL结构非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM