Merge Your CSS and JavaScript Using PHP

Merge all of your CSS and JS into one file to improve server speed.

Inside the body tags on your pages

<link href="css/css.php?set=<?php echo base64_encode(serialize(array('screen','index','boxes'))); ?>" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="js/js.php?set=<?php echo base64_encode(serialize(array('general','popup','tooltip'))); ?>"></script>

yoursite.com/css/css.php

 
header("Content-type: text/css");
if(isset($_GET['set'])) {
        $files = unserialize(base64_decode($_GET['set']));
        if (!empty($files)) {
                foreach($files as $file) {
                        $contents = file_get_contents(dirname(__FILE__).'/'.basename($file).'.css');
                        $data[] = $contents;
                }
        }
        echo implode("\n",$data);      
}

yoursite.com/js/js.php

 
if(isset($_GET['set'])) {
        $files = unserialize(base64_decode($_GET['set']));
        if (!empty($files)) {
                foreach($files as $file) {
                        $contents = file_get_contents(dirname(__FILE__).'/'.basename($file).'.js');
                        $data[] = $contents;
                }
        }
        echo implode("\n",$data);      
}

Post new comment

  • Allowed HTML tags: <b> <br> <p> <a> <strong> <cite> <em> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You may use [img:xx] tags to display uploaded files or images inline.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options