Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Dynamically compress css and javascript files

One way to speed up your page loading time is to optimize all files needed for your website. For example, more file takes space (Kb, Mb, etc), more time it needs to be downloaded to end users computer to view your website. So if you make those file lesser, they will load faster.

What are the options? For example, you can take all comments and spaces from your css and javascript files. Comments and spaces are important in development, but to end-user it doesn't matter, because browser will interpret them correctly without comments and spaces.

So to do that, you can use these code snippets. Just include all files needed to be compressed through php like in example.

Thise one is for css files:

<?php
//tell browser this would be a css file
header('Content-type: text/css');

//start output buffer and coll function compress in the end
ob_start("compress");

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

//include all you css file here
include("style.css");
include("/design/main.css");

ob_end_flush();
?>

And this one is for javascript files:

<?php
//tell browser this would be a javascript
header("content-type: application/x-javascript");

//start output buffer and coll function compress in the end
ob_start("compress");

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

/// include all you javascript files 
include("script.js");
include("/jquery/script.js");

ob_end_flush();
?>

Save those code snippets as php files, for example css.php and js.php and include them like you usually do:

<link rel='stylesheet' type='text/css' href='/css.php'>
<script type="text/javascript" src="/js.php"></script>

There are also many static methods, where you save compressed files and include them to your webpage, like minify, but every time you make a change in css files, you'll need to re do compressing operation again.


You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus