Phil
Phil

Reputation: 4069

execute javascript as coldfusion page loads

I have a ColdFusion page that on it, has several cfinclude template calls which include separate files into the page. I would like to update a javascript variable before each cfinclude template call. I've tried using:

<script type="text/javascript">
myvariable = 'new status';
</script>

However, the javascript doesn't get executed until every single template included on the page finishes processing, instead of before each one executes.

Is there some way I can actually execute javascript code AS the page loads?

Upvotes: 2

Views: 2594

Answers (1)

Digital Chris
Digital Chris

Reputation: 6202

You can accomplish this with <cfflush>.

CFFlush will send the current HTML/javascript output to the browser as it continues to process. It would look something like this:

<CFInclude template="process1.cfm">
<CFoutput>
    <script type="text/javascript">
    myvariable = 'new status';
    </script>
</CFoutput>
<cfflush>
<CFInclude template="process2.cfm">

... and repeat.

The javascript will be interpreted by the browser as soon as it is loaded. This sometimes causes unpredictable behavior since the DOM is not complete and in a ready state, but for simple operations it works.

Edit: note that you often have to pad your output with something like <cfoutput>#repeatString(" ", 250)#</cfoutput> before the browser will process it. See http://www.raymondcamden.com/index.cfm/2006/11/29/A-Loading-page-with-CFFLUSH-and-JavaScript

Upvotes: 5

Related Questions