Combining and Compressing multiple JavaScript file

2019-01-13 14:31发布

I am working on a PHP app that requires eight javascript files (hello web2.0).

I am wondering what the best way combine and compress all of the files dynamically. Am I phrasing the question correctly?

The end result is that I would include one .js file in the header, and that .js file would include of the .js files in my "includes/js" directory.

Thanks.

5条回答
再贱就再见
2楼-- · 2019-01-13 14:34

You can use jsmin-php

Their sample code is:

require 'jsmin-1.1.1.php';

// Output a minified version of example.js.
echo JSMin::minify(file_get_contents('example.js'));

You may easily join several js files by doing something like:

require 'jsmin-1.1.1.php';

// Output a minified version of example.js.
echo JSMin::minify(file_get_contents('example.js') . file_get_contents('example2.js'));
查看更多
欢心
3楼-- · 2019-01-13 14:38

You can try PHP SpeedyThis will combine and compress your JS Files for you into 1 single file. It will also compress your HTML and CSS and your page will load a lot faster.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-13 14:49

You maybe could use Yahoo JavaScript Compressor which is a command line tool you could start from you PHP script.

查看更多
【Aperson】
5楼-- · 2019-01-13 14:51

I've used Minify with my jQuery/PHP projects with lots of success. It includes caching too so there isn't much overhead.

I ended up changing things around and using .htaccess to route all requests to my javascript folder to the minify script, so for example:

<script type="text/javascript" src="/js/jquery.js,js/jquery-levitip.js,js/jquery-facebox.js,js/datepicker.js,js/ga.js"></script>

with my front-end HTML routes into my minify script and it returns all those scripts as one, compressed and minified. That way I can define the includes normally and everything happens behind the scenes.

But anyway check the user guide on their site, it's very well documented, and you should be able to pull things off the way you want too. Oh and it works for CSS too.

查看更多
放荡不羁爱自由
6楼-- · 2019-01-13 14:54
 function compress($buffer) {
        /* remove comments */
        $buffer = preg_replace("/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/", "", $buffer);
        /* remove tabs, spaces, newlines, etc. */
        $buffer = str_replace(array("\r\n","\r","\t","\n",'  ','    ','     '), '', $buffer);
        /* remove other spaces before/after ) */
        $buffer = preg_replace(array('(( )+\))','(\)( )+)'), ')', $buffer);
        return $buffer;
    }

Source: http://castlesblog.com/2010/august/14/php-javascript-css-minification

查看更多
登录 后发表回答