Andrew Perkins, a colleague of mine, wrote this HeaderBuilder component that comes handy when you need to load dynamically javascript and styles to your application, so each page will hold only its respective scripts.

I will show you how to use it in an application using FW/1 (Framework One) by Sean Corfield.

First thing to do is to download HeaderBuilder component, unzip it to the ‘org’ folder in your application: org.aperkins

Then instantiate the component in your Application.cfc in the SetupRequest() function, which will create the object on every request. Since this component is very simple, there are no functions in it to take care of garbage collection or clearing the object, so it is not recommended to add it in the SetupApplication as a singleton, otherwise it would continue to add scripts and styles from all controllers.

Here is the code for a sample application. Your file structure should be like this:

Sample Application File Structure

Instantiating the object in your Application.cfc:

public void function setupRequest(){
        variables.rc.oHeader = new com.aperkins.headerBuilder();

Setting scripts and styles in your controller:

public void function default(required struct rc){
        // add here your CSS and Javascripts for the default page
        variables.rc.oHeader.setPageTitle('This is the default page');
        // write here your controller for the default page

Loading the scripts and styles in your layout:

	<!--- Set title from the header object --->
	<!--- Load javascript and css from the header object that is set by the controller --->

You may download the entire sample application here.

I hope that helps you writing neat code.


Leave a Reply