1

I have some JavaScript, which is generated by PHP code, using a template.

The result of the template is a file contain JavaScript but with statements scattered through out it.

I want to reduce the size of this file by removing white space and comments.

However all I can find on the web are tools for plain JavaScript, which are extremely complex.

I have all ready write a script to reduce HTML, and CSS based content using the same system, I'm looking for info on reducing the size of JavaScript file so I can write a reduction script that can handle the PHP code being in the file.

So what I want is:

A tutorial for reducing the size of JavaScript code. A simple to follow script for reducing JavaScript size I can analysis. Or a Tool that works fine with PHP inline with the JavaScript Code (Must be either Public Domain, or Open Source allowing for use in commercial works)

EDIT:

$script = preg_replace('%/\*.*?\*/%','',$script);
$compress = preg_split('%("|\'|/)(?:\\\\|\\\1|[^\1])*?\1|<\?php\s+(?:("|\')(?:\\\\|\\\2|[^\2])*?\2|[^"\']*?)*?\?>%',$script);
preg_match_all('%(("|\'|/)(?:\\\\|\\\2|[^\2])*?\2|<\?php\s+(?:("|\')(?:\\\\|\\\3|[^\3])*?\3|[^"\']*?)*?\?>)%',$script,$no_compress);
foreach ($compress as &$block) { $block = preg_replace('%\s+%',' ',$block); }

I think I've solved it, the above should remove C-style comments, then split the remaining code around PHP blocks, Javascript Strings ' or ", and Regex Patterns /, and also extract the code blocks, strings, and Regex Patterns, Code inside a Pattern or String should be ignored as its second the Option in Regex. The Final line should reduce the white space in the compress blocks to a single space

Then It should just be a matter of recombination of the blocks, i.e.

$cscript .= $compress[$i].$no_compress[$i]

To rebuild the script.

Any thing I've missed?

2 Answers 2

6

Do you want something like this?

http://code.google.com/p/minify/

Sign up to request clarification or add additional context in comments.

2 Comments

hey! it is awesome. Just a question. can i use it on production server? i mean it will not create any issue or vulnerability
Also i want to implement it in Zend. What is the best way?
0

By dynamic javascript you mean javascript that has PHP tags scattered through it? If thats the case then you REALLY ought to find new programming methods Like a JSON stream. I have also used payloads in my sites and that might be a method you'd conciser other than PHP JS. You might be able to use a generic PHP and JS Minifier to make the PHP page smaller. Good luck.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.