September 5th, 2008

Recently I’ve been working on PHP mailing list tool, and I wanted to make a simple Javascript API so that users can place dynamically generated gadgets onto their own pages. I wanted one JS file that could be included on a page, but as I was using a 3rd party AJAX Javascript library, this also had to be included. Unfortunately Javascript has no concept of an include or import statement. So my solution was to use some PHP to merge them on the server:

<?php header('Content-Type: application/x-javascript'); ?>
/**
 * This file is a server-side merge of first.js and second.js
 *
 * ------------------------------ first.js -------------------------------
 */
 
<?php echo file_get_contents('first.js'); ?>
 
/**
 * ---------------------------- second.php ----------------------------
 */
 
<?php echo file_get_contents('second.js'); ?>

This simple approach could be used where you’ve got a lot of JS files and you want to speed up access times.

Leave a Reply