Share and Enjoy

Best practices for deployment and development of CSS and JS files

When working on a big size web based application, static files (Javascripts, Stylesheets and Images) are something you should handle with care. While you’re back-end can be a breeze for server, a front-end without best practices can cause your website to load slow thus resulting in loosing visitors/customers. There are many tips that can make your website load much faster and In this article I am going to write about how you can adopt those techniques.

Load Stylesheets JS Files in correct places

When writing markup you should make sure that you have all you stylesheets in the document HEAD, consider the following example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>My site title</title>
 <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/feeds.xml" />
 <link rel="shortcut icon" href="/static/images/favicon.ico">

 <link rel="stylesheet" href="/static/styles/styles.css" type="text/css" media="screen" />
 <link rel='stylesheet' href="/static/styles/colors.css" type="text/css" media="all" />
 <link rel='stylesheet' href="/static/styles/portfolio.css" type="text/css" media="all" />

On some browsers, Internet explorer precisely, you must have noticed that when opening a site, you see a white page and whole content appears suddenly. This is caused by putting stylesheets outside HEAD of the document. According to Yahoo Developers Network, putting stylesheets outside HEAD prohibits progressive rendering in many browsers, including Internet Explorer.

SCRIPTS case in totally different with stylesheet’s. You should put the scripts at the end of the document, right after BODY ideally. Scripts don’t allow parallel downloads, with means if you have a 70 KB javascript file in your HEAD, rest of the stuff on page like images or stylesheets will have to wait until that javascript is downloaded on client. In most of the cases, its not easy to move SCRIPTS to bottom, but if you are working on a project from scratch you should write your code with this pratice in mind.

Write correct CSS and Javascript

Avoid writing inline CSS and Javascript, instead make those that external. Javascript and CSS files are cached by browsers resulting quick page loading. On the other hand, CSS and Javascript coded in HTML document gets downloaded every time page is loaded. And even apart from speed issues, its a bad development practice to mix up different stuff in one file. Don’t use garbage like CSS expressions or BS like DEFER (use I hate IE).

Include minimum Javascript and CSS files

Instead of including multiple CSS and JS files, you should include one master file for each, like instead of including prototype.js, effects.js, modules.js as separate file, include a single file something like common,js that contains the code all above three files.

The problem with this practice is that it increases development time if you put all code in a single file. Or if you are making separate files for development and merge those at time of deployment, that itself is a big problem. At the end of this article, I will suggest a solution for this problem, I am sure you’ll find that deadly useful.

Use compressed Javascript and CSS

Compressing the Javascript and CSS can also help in reducing load time of web pages. You can use following online tools to compress the your files.

You can imagine that a 100KB file compressed to 60KB will be faster in download.

Problems and the Solution

But the main issue with compressing the files is that it can result in increased time of deployment. You can’t write, edit or understand Javascript in a single line, so before deployment you have to compress your files before uploading. To make the development and deployment cycle a bit smooth, I have adopted a technique which I archived by extending the great article written here.

Basically, rather than using the static files after compressing and minimizing the static content into one files ourselves manually, I am using the server side to do that all stuff. A PHP script will include different files as a singe file, compress those file and will send the output to those files. Following the code of file static.php

//static.php

// Change folowing path to according to your needs
$_pathToStatic = '/home/mysite/templates/static/';

$_type = $_GET['type'];
$_load = explode(',', $_GET['load']);

if($_type == 'css')
{
	header('Content-type: text/css');
	$ext = '.css';
}
else
{
	header('Content-type: text/javascript');
	$ext = '.js';
}

ob_start("compress");

function compress($buffer)
{
	/* remove comments */
	$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
	/* remove tabs, spaces, newlines, etc. */
	$buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
	return $buffer;
}

foreach($_load as $load)
{
	$_file = $_pathToStatic.trim($load).$ext;
	if(file_exists($_file))
		include($_file);
}

 ob_end_flush();

The above file basically takes the parameter of which and what type files to include. On the bases parameters, script includes those files from the directory defined in line 2, compress the content and send to browser. So this way, your web page makes only one request for both CSS and Javascript and gets the output in compressed form. You don’t have to write all CSS and JS in one file, and have to compress that when deploying.

Now to use the above file, use the following code,

<link rel="stylesheet" href="static.php?type=css&load=common,layout,colors,typography" type="text/css" media="screen" />
<script type="text/javascript" src="static.php?type=js&load=prototype,effects,builder,dragdrop,modules"></script>

In the type parameter, you have to enter either css or js, based on what files you are including. And load parameter takes the comma separated values of files to be included.

As most of the browsers don’t cache dynamic files (like .php), so there are chances that files included this way will be download on every request. To prevent this, we can use Apache’s rewrite rule.

RewriteEngine on
RewriteRule ^static.([a-z]+)$ static.php?type=$1 [QSA]

Now you’re code to include files now look like

<link rel="stylesheet" href="static.css?load=common,layout,colors,typography" type="text/css" media="screen" />
<script type="text/javascript" src="static.js?load=prototype,effects,builder,dragdrop,modules"></script>

If you find any bugs/problems/suggestions or do some improvements, please do share those with us by commenting.

Enjoyed this Post?

Share and Enjoy

Facebook Feeds