Using CFHTMLHEAD
Feb 9
Last week one of my team members gave a presentation to the rest of us on Coldbox. We are using this framework for a project and we were discussing the basics of convention and how to work with the different layers - which brought up the question, where exactly is the optimal place to put the Javascript in this?.
I used this opportunity to bring up the CFHTMLHEAD tag, which allows you to place code into the head tag from anywhere on the page. This would allow us to keep Javascript from loading on unnecessary pages and still keep everything componentized. I also thought this would be a good opportunity to discuss basic CFHTMLHEAD usage.
The Adobe docs say "Use this tag for embedding JavaScript code, or putting other HTML tags, such as meta, link, title, or base in an HTML page header. If you use this tag after the cfflush tag on a page, an error is thrown."
This is a very simple yet powerful tag with one attribute, which is required, text. A very basic usage example is below:
2
3 <cffunction name="myFunction">
4 <cfsavecontent variable="my_head">
5 <!-- myComponent.myFunction -->
6 <script src="/scripts/script1.js" type="text/javascript"></script>
7 <script src="/scripts/script2.js" type="text/javascript"></script>
8 <link type="text/css" href="/styles/style1.css" rel="stylesheet" />
9 </cfsavecontent>
10
11 <cfhtmlhead text="#variables.my_head#">
12 </cffunction>
13
14</cfcomponent>
Note how I included a regular HTML comment just above the content that will be included in my head tag. This is so that if I need to debug, I can easily figure out where to look. Though I haven't had the pleasure of debugging from a CFHTMLHEAD tag yet, I read a blog entry by Ben Nadel on this topic a while ago and thought this was a great idea, just in case.
Team Ravenglass