开发者

How can I output a single-line JavaScript from a PHP object?

My PHP code:

include "something开发者_如何学JAVA.php"
$mysite = writeContent();

//footer.php
ob_start();
echo "<script...all my javascript here...</script>";
$object = ob_get_contents();
ob_end_clean();

$search = array("\n","\r");
$replace = array("","");
$object = str_replace($search, $replace, $object);
echo $object;

then my JavaScript is malformed and doesn't work.

I know I can use gzip to increase the speed (thats not what I'm asking) but what I really want is to remove the extra space from the code.


Any chance you're having an issue with semicolons? You probably want to validate your JavaScript first to see what's wrong, but here's one of many possibilities:

var foo = 0 // This works fine
var bar = 1
// #=>
var foo = 0var bar = 1 // This doesn't

// And FWIW, this is what you want:
var foo = 0;
var bar = 1;


Ideally, you'd LINT your JS, then run it through a properly tested minifier. For PHP, I have used jsmin-php with great success.


Since Josh didn't make his comment an answer, I will.

When you replace your newlines and your JavaScript is missing semi-colons, the interpreter has no way detect the end of statements. Therefore, just make sure every single line in your script has a ";". Alternatively, you could replace all the new lines with semi-colons, two semi-colons in a row is not a syntax error. Not ideal but will do the trick.

JAAulde's suggestion, run it through a minimizer is the best way. Here's one for php https://github.com/rgrove/jsmin-php/

See Combining and Compressing multiple JavaScript files in php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜