How to minify JS or CSS on the fly [closed]

Asked
Active3 hr before
Viewed126 times

7 Answers

closed
90%

Server compressed contents (gzip/compress/deflate),Add Character Encoding to your response,Minify Inline CSS and JS code blocks,Minify JS, CSS files on the fly

After a lot of searching and sites optimizations i really recommend to use this script for CSS files:

<style>
<?php
     $cssFiles = array(
      "style.css",
      "style2.css"
    );

    $buffer = "";
    foreach ($cssFiles as $cssFile) {
      $buffer .= file_get_contents($cssFile);
    }
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    echo($buffer);
?>
</style>
load more v
88%

How to minify JS and CSS on the fly / runtime, so that I can keep the original code structure in my servers if its minified on the runtime / fly.,It does the minification and merging on the fly. It also has caching to avoid reruning the minification or reprocessing of a resource if resource not modified. It also helps with following optimizations.,Generally runtime minification should always be combined with solid caching on the server side and the usage of client and proxy caches along the way to the browser. ,If your goal is to make your JavaScript slightly less readable, and do this at runtime, you could keep it very, very, simple. With just three lines of code you can get a long way toward total minification within a few milliseconds.

After a lot of searching and sites optimizations i really recommend to use this script for CSS files:

<style>
<?php
     $cssFiles = array(
      "style.css",
      "style2.css"
    );

    $buffer = "";
    foreach ($cssFiles as $cssFile) {
      $buffer .= file_get_contents($cssFile);
    }
    $buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(array("
", "
", "
", "	", '  ', '    ', '    '), '', $buffer);
    echo($buffer);
?>
</style>
load more v
72%

Here is a list of some helpful tools to get your started. Since many of these can minify more than one code type, I’ve included the code type options in parenthesis.,refresh-sf.com (HTML, CSS and JS) – This compressor will minify JavaScript, CSS and HTML code types. It also includes all the compressor options for each code type if you need them.,Then go back to the css file of your website and replace the code with the new minified version.,A fantastic article, to many sites are not optimised and this is something we talk about a lot at our studio. Everybody has their own ways in introducing minify to clients.

CSS Before Minification

/* Layout helpers

----------------------------------*/
.ui - helper - hidden {
      display: none;
   }
   .ui - helper - hidden - accessible {
      border: 0;
      clip: rect(0 0 0 0);
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
   }
load more v
65%

As web applications become richer and more complicated the amount of JavaScript running them increases. More code means longer download times which means more waiting before your application or web site is usable. Thankfully there’s an easy solution that’s already widely used in the web development community: minification. Minified JavaScript strips whitespace and renames variables to produce a smaller download size.,You can take this one step further by wrapping your code in immediately-invoked function expressions (IIFEs). That’s a pretty scary looking name, but chances are you’ve seen these before, this is an example:,With script minification the above code will be changed to this:,without altering the behavior of the function. As you can see, all whitespace that can be removed has been and the variable “name” was changed to “a“. The end result is the removal of 26 characters from the code. It’s not hard to see that the savings from minification will quickly add up!

without altering the behavior of the function. As you can see, all whitespace that can be removed has been and the variable “name” was changed to “a“. The end result is the removal of 26 characters from the code. It’s not hard to see that the savings from minification will quickly add up!

name

without altering the behavior of the function. As you can see, all whitespace that can be removed has been and the variable “name” was changed to “a“. The end result is the removal of 26 characters from the code. It’s not hard to see that the savings from minification will quickly add up!

a
load more v
75%

I don't get it. Do you want that code translated, and have it all run locally, or do you want to send a request to a webserver with that code uploaded?,There are rules that state you must have attempted it yourself; we will not do your homework for you. Read up about it. Wouldn't be too hard., Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions. ,The former: Translated code running locally.

Below is the PHP script I'm working from.

< ? php

// Get file list
$files = array();
foreach(explode('&', $_SERVER['QUERY_STRING']) as $file) {
   $files[] = urldecode($file);
}

/*
TODO: use cache if none of the requested files have been updated since cache was created (check modification times)
*/

// Ensure no funny file paths
foreach($files as $file) {
   if (is_file("wwwroot/$file") and strpos(realpath("wwwroot/$file"), realpath('wwwroot')) !== 0) {
      bad_request();
   }
}

// Determine if JS, CSS or something else is being requested
$reqJS = false;
$reqCSS = false;
$reqOther = false;
foreach($files as $file) {
   $file = strtolower($file);
   if (substr($file, -3) == '.js') {
      $reqJS = true;
   }
   elseif(substr($file, -4) == '.css') {
      $reqCSS = true;
   }
   else {
      $reqOther = true;
   }
}

// Ensure only JS or only CSS files are requested
if ($reqJS and $reqCSS or!$reqJS and!$reqCSS or $reqOther) {
   bad_request();
}

// Set header
if ($reqJS) {
   header('Content-type: text/javascript');
} else /* assume CSS */ {
   header('Content-type: text/css');
}

// Get file data
$data = '';
foreach($files as $file) {
   $file = "wwwroot/$file";
   if (is_file($file)) {
      $data. = file_get_contents($file);
   }
}

// Compress data
// Fork the java process
$cmd = 'java -jar "'.realpath('bin/yuicompressor.jar').
'" --type '.($reqJS ? 'js' : 'css');
$descriptors = array(
   0 => array('pipe', 'r'),
   1 => array('pipe', 'w'),
   2 => array('pipe', 'w')
);
$process = proc_open($cmd, $descriptors, $pipes);
if ($process === false) {
   internal_server_error();
}

// Feed the data to the compressor
fwrite($pipes[0], $data);
fclose($pipes[0]);

// Read back the compressed data
$compressed = stream_get_contents($pipes[1]);
fclose($pipes[1]);

// Check for errors
$errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);

// Close the process
$exitStatus = proc_close($process);

// Check if unsuccesful
if ($exitStatus != 0 or $errors != '') {
   internal_server_error();
}

/* TODO: cache compressed output */

echo $compressed;

function bad_request() {
   header('HTTP/1.1 400 Bad Request');
   exit;
}

function internal_server_error() {
   header('HTTP/1.1 500 Internal Server Error');
   exit;
}
load more v
40%

I am trying to minify CSS, HTML, JS , PHP on the fly;,I am planning to use below script., Minify CSS JS HTML on the fly Speeding Oscommerce 2.3.4 ,The Major issue is that I am not able to figure out how to trigger this script in oscommerce to optimize on the fly....

I plan to include below file in template_top.php;

include 'includes/php-html-css-js-minifier.php';
load more v
22%

Posted 08 July 2010 - 01:38 AM , Posted 08 July 2010 - 11:11 AM , Posted 08 July 2010 - 06:12 AM , Posted 08 July 2010 - 04:17 AM


< ? php

// Get file list
$files = array();
foreach(explode('&', $_SERVER['QUERY_STRING']) as $file) {
   $files[] = urldecode($file);
}

/*
TODO: use cache if none of the requested files have been updated since cache was created (check modification times)
*/

// Ensure no funny file paths
foreach($files as $file) {
   if (is_file("wwwroot/$file") and strpos(realpath("wwwroot/$file"), realpath('wwwroot')) !== 0) {
      bad_request();
   }
}

// Determine if JS, CSS or something else is being requested
$reqJS = false;
$reqCSS = false;
$reqOther = false;
foreach($files as $file) {
   $file = strtolower($file);
   if (substr($file, -3) == '.js') {
      $reqJS = true;
   }
   elseif(substr($file, -4) == '.css') {
      $reqCSS = true;
   }
   else {
      $reqOther = true;
   }
}

// Ensure only JS or only CSS files are requested
if ($reqJS and $reqCSS or!$reqJS and!$reqCSS or $reqOther) {
   bad_request();
}

// Set header
if ($reqJS) {
   header('Content-type: text/javascript');
} else /* assume CSS */ {
   header('Content-type: text/css');
}

// Get file data
$data = '';
foreach($files as $file) {
   $file = "wwwroot/$file";
   if (is_file($file)) {
      $data. = file_get_contents($file);
   }
}

// Compress data
// Fork the java process
$cmd = 'java -jar "'.realpath('bin/yuicompressor.jar').
'" --type '.($reqJS ? 'js' : 'css');
$descriptors = array(
   0 => array('pipe', 'r'),
   1 => array('pipe', 'w'),
   2 => array('pipe', 'w')
);
$process = proc_open($cmd, $descriptors, $pipes);
if ($process === false) {
   internal_server_error();
}

// Feed the data to the compressor
fwrite($pipes[0], $data);
fclose($pipes[0]);

// Read back the compressed data
$compressed = stream_get_contents($pipes[1]);
fclose($pipes[1]);

// Check for errors
$errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);

// Close the process
$exitStatus = proc_close($process);

// Check if unsuccesful
if ($exitStatus != 0 or $errors != '') {
   internal_server_error();
}

/* TODO: cache compressed output */

echo $compressed;

function bad_request() {
   header('HTTP/1.1 400 Bad Request');
   exit;
}

function internal_server_error() {
   header('HTTP/1.1 500 Internal Server Error');
   exit;
}

Other "closed-undefined" queries related to "How to minify JS or CSS on the fly [closed]"