2

My PHP code:

include "something.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.

Lipis
  • 21,388
  • 20
  • 94
  • 121
braindamage
  • 2,226
  • 4
  • 24
  • 33
  • 2
    Just be sure to have semicolons at the end of every line and brackets everywhere you could possible put them and it should work fine... Can you provide an example of your 'broken' JS? – josh.trow Jun 15 '11 at 19:23
  • 1
    Please can you add an example of the JavaScript you want to output and the malformed result? – andyb Jun 15 '11 at 19:24
  • FWIW, just because you use an array for the search portion of `str_replace` doesn't mean you need an array for the replace. You can just give it a single empty string. – JAAulde Jun 15 '11 at 19:40
  • thanks josh, i would accept that but you didnt make a reply, that was the problem ;] – braindamage Jun 15 '11 at 19:40

3 Answers3

2

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

JAAulde
  • 19,250
  • 5
  • 52
  • 63
  • include "includes/jsmin.php"; echo JSMin::minify($object); = NICE! – braindamage Jun 15 '11 at 19:49
  • Yeah, I use it quite heavily in a large system, along with CSSMin-php. We combine and minify our stuff on the fly and write it to a cache file with a hashed name so that it doesn't have to be recombined and minified on the next page load. – JAAulde Jun 15 '11 at 19:53
2

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;
brymck
  • 7,555
  • 28
  • 31
2

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

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217