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.
Then you write your view and pump your javascript to inject.
Then you write your page with those components in it.
This will ultimately yield this:
In the future, I'd like to see us solve this problem natively, like but until then here's a solution.
8 responses so far ↓
1 Dan G. Switzer, II
Instead of injecting to the request scope, just create a child element for your cf_pageWrapper tag, called cf_pageFooter.I use this basic concept in the code base I'm currently working on.
2 Matt Gersting
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
3 tpryan
@Dan I'm not sure I follow. The Request scope is used because it is accessible from every page call.@Matt, cool project.
4 Henry Ho
Thank you! What a coincident, I blogged about this earlier today too.http://henrylearnstorock.blogspot.com/2010/08/terrence-ryan-taught-me-why-is-not.html
@Matt, ScriptWriter looks interesting.
5 Mike Collins
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.
6 Jules Gravinese
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}
7 tpryan
@Jules, cause it isn't about delayed execution, it's about putting javascript in the footer for performance reasons.8 Jules Gravinese
@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.
Leave a Comment