Ricky Yoder
Ricky Yoder

Reputation: 571

Minify Inline-JavaScript with PHP

Currently for my site, I'm able to minify JavaScript and CSS code through linked <link> and <script> tags.

Example:

<script src="/inc/php/jsmin.php?f=inc/js/core.js"></script>

But, to reduce HTTP requests, I have inline scripts and styles as well. I also have inline scripts and styles because I don't need everything included on every page I make.

Is there a way I can use PHP DOM or something else to minify code on the same file that the script is running on?

Upvotes: 1

Views: 3066

Answers (1)

Joe
Joe

Reputation: 15528

You could do doing something like this:

<?php require '/inc/php/jsmin.php'; ?>

// your regular html here

<?php echo JSMin::minify(file_get_contents('js/page-name/your-old-inline.js')); ?>

// your regular html here

The approach I would take is to take the inline JS and move it into separate files then use jsmin.php to minify the file. This reduces the HTTP requests and the overhead of file_get_contents() is relatively small.

Upvotes: 3

Related Questions