BoA456
BoA456

Reputation: 341

PHP minify function seems to destroy inline JS?

I have the following minify function:

public static function minify($buffer)
{
    $search = array(
        '/\>[^\S ]+/s',
        '/[^\S ]+\</s',
        '/(\s)+/s'
    );
    $replace = array(
        '>',
        '<',
        '\\1'
    );
    $buffer = preg_replace($search, $replace, $buffer);
    return $buffer;
}

This function is used with ob_start() in order to minify my html output. The function is taken from here: https://stackoverflow.com/a/6225706/4601581

This function seems to destroy some of my JS. Example: A button i click to execute some JS:

<button type="button" class="btn btn-<?= Config::$ELEMENT_COLOR ?> btn-block" onclick="addLastInput(<?= $mask->getId() ?>)">Do it</button>

The $id i give to addLastInput is simply a number, taken from $mask->getId().

Also i have this little JS code to populate some data array:

<script>lastSubmissionData[<?=$mask->getId()?>] = '<?=json_encode($lastSubmissionData)?>';</script>

And finally my JS function i actually want to execute with my given param (the id) and on the data array:

function addLastInput(maskId) {
        var data = lastSubmissionData[maskId];
        for (var i = 0; i < data.length; i++) {
            // TODO
        }
    }

Whenever i only load the page, it simply tells me Uncaught SyntaxError: Unexpected end of input in the Chrome console. Whenever i do so with not using the minify function and outcommenting the ob_start() completely, it just works and i can use it.

Conclusion: The minify function seems to brake my inline JS as the comments on the linked SO answer suggest. Question: How can i fix that? I even googled for other minify solutions like this one: https://gist.github.com/tovic/d7b310dea3b33e4732c0

All of them seem to not work by just breaking my site. What's the best solution here to simply let me use my JS code and still minify my html output?

Upvotes: 0

Views: 409

Answers (1)

user149341
user149341

Reputation:

Don't use this minify() function. It's broken.

This function ends up removing some semantically meaningful newlines in inline Javascript code, such as ones appearing at the end of a single-line comment. (For example, it converts your example Javascript function to a single line ending in { // TODO } }.)

This function will break some HTML constructs as well. In particular, it will destroy the content of <pre> tags, as it does not recognize that whitespace is significant in that context.

(Both of these caveats are mentioned in highly upvoted comments on the post you got this code from, by the way!)

Upvotes: 1

Related Questions