I am looking at optimization options, and after checking SO questions, I don't quite see an ans开发者_如何学Cwer for what I am trying to do. Hopefully that doesn't indicate that what I am doing is a bad practice!
I have an intranet application that loads page content via ajax calls to php files. A lot of the php files have a mixture of php, JavaScript, even some HTML, specific to the interface functionality that they load into the main interface. I was wondering about minifying or compressing these files. Is there a way to do it, or am I stuck because I have mixed languages?
Update: Concerning accepted answer:
I have accepted wildpeaks answer because I think it most closely answers my original question. However, this is one of those times when I wish I could accept two answers because I think the answer Igor Zinov'yev provided has given me perhaps a more important design decision to think about. For that reason I have given a +1 to his answer, as I imagine others will too. Hope that makes sense and is within the SO rules.
Your PHP script generates the Javascript code, so it can minify the code before outputting it: generate the code in a variable, then pass that variable to the minifier, and only then output to the browser.
Here's a PHP library for that.
You are starting your optimization off the wrong end. Obviously if you have hard-coded JavaScript, HTML and whatever else inside your PHP files, you seriously need to refactor the code. But even if you don't, you shouldn't minify the code in place because it would be even harder to maintain.
Pull it out of there, start with small steps, and you will get there eventually.
UPDATE: I thought of replying with a comment, but instead decided to elaborate on why I answered your question this way here.
I'm talking here about separation of concerns. Your server-side code files are no place for the client-side code. All solutions that do this that I have seen so far sooner or later turn into an unmaintainable mess.
If you want to return a piece of HTML code, put it into a template and supply the template with variables that are specific for this current situation. You can do that with Smarty. This way you get among others the following benefits:
- No repeating pieces of markup over and over - there are template loops for that
- A possibility to re-use existing templates in several places
- Developers working with templates do not need to get into your server-side code
- And your server-side code gets cleaner, smells nice too!
Later on when you separate logic from presentation maybe you will find that you don't need to send JavaScript code with HTML snippets. Maybe you will create a single JS engine (that you will minify on build) and will only have to trigger certain events upon load.
精彩评论