01/07/2010 11:23pm

PHP | Working Example - Use Combined files for CSS and Javascript


<?php


class Page_Controller extends ContentController {

public function init() {

parent::init();

$combinepath = 'themes/'.SSViewer::current_theme().'/combined';
Requirements::set_combined_files_folder($combinepath);

$css = array();
$css [] = "themes/".SSViewer::current_theme()."/css/layout.css";
$css [] = "themes/".SSViewer::current_theme()."/css/form.css";

global $GMapApi;
Requirements::javascript("http://maps.google.com/maps?file=api&amp;v=2&amp;key=".$GMapApi."&amp;hl=nl");

$js = array();
$js[] = 'sapphire/thirdparty/jquery/jquery-packed.js';

$js[] = 'mysite/javascript/roundedcorners.js';
$js[] = 'mysite/javascript/gmap.js';
$js[] = 'mysite/javascript/fn.js';
foreach($css as $c){
Requirements::css($c);
}

foreach($js as $j){
Requirements::javascript($j);
}

if(Director::isLive()){
Requirements::combine_files('combined.css',$css);
Requirements::combine_files('combined.js',$js);
Requirements::process_combined_files();
}

//compress the styles on flush :)
if(isset($this->request) && $this->request->getVar('flush') == 'all'){
if(file_exists(Director::baseFolder() . '/' .$combinepath.'/combined.css')){
$bf = file_get_contents(Director::baseFolder() . '/' .$combinepath.'/combined.css');
$bf = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $bf);
$bf = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $bf);
$fh = fopen(Director::baseFolder() . '/' .$combinepath.'/combined.css', 'w');
fwrite($fh, $bf);
fclose($fh);
}
}
}
}

Put the files to combine in a seperate array, to allow some files to be excluded.

I put the combined files in the theme folder, so image paths stay correct.

Tags : Combine files css javascript

Post Comment