0

I have a javascript function receiving php arrays like this :

let options = <?php echo $arrayoptions; ?>;
let optlibs = <?php echo $arrayoptlib; ?>;
let forms   = <?php echo $arrayforms; ?>;

It works well but problem arises when I try to minify function. All minifiers I tried gave en error with php part. What can I do ?

  • 2
    Don't construct dynamic JS like that. If I were you, echo into a ` – CertainPerformance Aug 20 '22 at 23:08
  • You really should JSON encode any values you emit that way, like with [`json_encode`](https://www.php.net/manual/en/function.json-encode.php). – tadman Aug 20 '22 at 23:16
  • All arrays are json_encoded .I'm going to try ouput in a hidden div solution. Thx. – Alex Leguevaques Aug 20 '22 at 23:18
  • Usually JavaScript is minified because it's static, meaning it doesn't change. Injecting PHP defeats the value of minification because the overhead of minifying is incurred on every request. If the PHP variables are configuration values and don't change frequently, you can code a module (short JavaScript file) with just the PHP values in it. – user2182349 Aug 21 '22 at 00:43
  • you’re right I need arrays from postgresql so I’m going to isolate dynamic part. – Alex Leguevaques Aug 21 '22 at 11:19

1 Answers1

0

Yes, you will run into errors because PHP is not part of Javascript syntax. Even your Javascript part for the arrays seems dynamically generated by PHP. This will be impossible to handle.

The only way to work around this would be modify your javascript to fetch those arrays and store them somewhere your whole script can access them for later use.

Then, the script can be minified without issue since PHP syntax are no longer part of it.

Bhad Guy
  • 80
  • 7