Injecting JavaScript to the foot of a ColdFusion Page

A question came up on Twitter today:

hard to do “JavaScript at the bottom” in CFML with MVC frameworks… wish we have a tag. Thought? #coldfusion

A great question, this is the answer in Adobe ColdFusion.

Use the request scope.

This is one of those random places where request scope is actually very helpful.  It breaks encapsulation, but you’re going to have to do that anyway.

So first you write a page wrapper, that displays the content of a variable named request.footer.

http://gist.github.com/541051.js?file=pageWrapper.cfm

Then you write your view and pump your javascript to inject.

http://gist.github.com/541051.js?file=uiWidget.cfm

Then you write your page with those components in it.

http://gist.github.com/541051.js?file=index.cfm

This will ultimately yield this:

http://gist.github.com/541051.js?file=results.html

In the future, I’d like to see us solve this problem natively, like but until then here’s a solution.

8 thoughts on “Injecting JavaScript to the foot of a ColdFusion Page

  1. FWIW, I wrote and use a CFC-based handler for this called ScriptWriter, so your model would contain statements like:

    Application.oScriptWriter.addScript(params);

    and your footer (or anything you want…you can have unlimited output regions) would go something like this:

    Application.oScriptWriter.outputScripts(region=’footer’);

    It supports inline javascript and css, and also can take care of minimization and file merging to limit the size and number of requests your page generates.

    http://scriptwriter.riaforge.com

    Like

  2. You might try OnRequestEnd.cfm too.

    Also, if using application.cfc – really nothing stopping you from including more files once your initial target has been called in the OnRequest method.

    Like

  3. Why not use scriptaculous or jquery to delay execution?

    Scripty version:
    {script type=”text/javascript” defer=”defer”}
    Event.observe(window,’load’, function(){
    …your js here…
    });
    {/script}

    Like

  4. @tpryan, Event.observe(window,’load’, function(){}); waits for the page to be fully loaded before executing its contents. I can’t imagine much of a difference.
    http://www.prototypejs.org/api/event/observe
    So isn’t that better and more intelligent (on terms of JS, not you/me/us) than simply putting js in the footer? Imagine a very heavy page with lots of resources, a js at the bottom of the HTML might be calling on images that haven’t even loaded yet. Observing for the load state of the window would be better.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s