cooking, programming and everyday life xrado

Wednesday, January 21, 2009

Simple combining of multiple javascript and css files

I've already wrote about "firefox only includes styles form .css files" and I found out that isn't quite true. Actually firefox doesn't care about the css file extension, but only relay on header Content-Type: text/css. If you as usual have .css file, apache will take care of right content-type, otherwise you will have to take care about it.
header('Content-Type: text/css');
I came across this when i was writing this script:
## combine.php

// Define path prefix
$prefix = realpath('.');

if(!empty($_GET['js'])) {
	header('Content-Type: application/x-javascript');
	$data = Array('path'=>$prefix.'/template/js/','files'=>$_GET['js'],'ext'=>'.js');
} elseif(!empty($_GET['css'])) {
	header('Content-Type: text/css');
	$data = Array('path'=>$prefix.'/template/styles/','files'=>$_GET['css'],'ext'=>'.css');
} else exit();

foreach(explode(',',$data['files']) as $file) {
	if($file && file_exists($data['path'].$file.$data['ext'])) readfile($data['path'].$file.$data['ext']);
}
Simple few lines of code, but already do the trick. That will minimise number of server requests and benefit in faster page loading.

Defining the path and file extension is important, otherwise you may expose some other scripts source or even worse, some system files.

Usage in page head
<link rel="stylesheet" type="text/css" href="combine.php?css=style,forms" />
<script type="text/javascript" src="combine.php?js=mootools,validate,fx"></script>
Hope you like it, otherwise If you want more advanced solution try minify.

cheers

Friday, October 17, 2008

firefox only includes styles form .css files

Tested with firefox 3.0.3, i don't know about previous versions. For instance, try to rename style.css to style.txt and include it into html header. Firefox show no style applied, while Internet Explorer 7 had no problems including .txt styles. I don't know why is that so, is this a bug or intended behaviour. I think that styles should be included regardless file extension, otherwise header link tag type=text/css have no meaning.