December 7, 2006

Including js files from within js files

I’m working on an application which stores a lot of data in the application scope. Part of the data stored is a config CFC that has a method which loads ‘external assets’ (javascript and css files etc) into the of the html document via . I love that tag :)

My part in this application development is limited to a particular section only, but there was already a lot of external assets present in the header and things were getting very messy. I was looking for a way to simulate but from within a .js file so I could clean up my output a bit, fortunately there is a way!

I now have a master js file to add to the section of my document:

<script src="js/master.js" type="text/javascript"></script>

From within this master.js file I can ‘include’ any js files I want.


//this function includes all necessary js files for the application
function include(file)

  var script  = document.createElement('script');
  script.src  = file;
  script.type = 'text/javascript';
  script.defer = true;



/* include any js files here */

The above code includes myFile1.js and myFile2.js, both of which are located in the relative ‘js/’ directory.

Not only does this clean up my output, but as my config file was stored in application scope every time I wanted to add/remove an asset from my application I need to refresh the scope…annoying. But now I am happy :)

© Michael Sharman 2017