1

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?

4
  • You can probably utilize the jsmin functionality by manually calling it within your scripts. You can easily use HEREDOC sections to output your inline Javascript after passing it through that minimizing filter; there seems no need for DOM/HTML post-processing. Commented Jun 23, 2013 at 21:28
  • You can, but it adds load to the server. Why not put your Javascript in one or two minified files which are included in every page. The files will be cached by the visitor's browser on the first request and will not be reloaded a second time. Also, if you're using JQuery, make sure to load them from the JQuery page or Google instead of hosting them yourself. Inline Javascript is only cached if the page itself is cached, which is less likely, especially if you have dynamic content, like news or user profile information. Commented Jun 23, 2013 at 21:29
  • "inline scripts and styles because I don't need everything included on every page I make." but if they are in an external file it will be cached so only called once Commented Jun 23, 2013 at 21:29
  • Do all mobile browsers cache content like this? And isn't there a limit if they do? Commented Jun 23, 2013 at 21:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I never really understood the ins and outs of file inclusion in PHP. Does it COUNT as an HTTP Request, or does it just put load on the server?
If your pages are php files then just use <?php require '/inc/php/jsmin.php'; ?> at the top of the page. Including it means that the class can be used on the page without writing all the PHP code in every file where it's required. Here's the doc page: php.net/manual/en/function.include.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.