0

I use JShrink with a custom function to combine 8 uncompressed JavaScript files to a single compressed (minified) one, like this:

<?php
// Filename: js.php 
header('Content-type: text/javascript');
require_once '../JShrink.php';

function concatenateFiles($files)
{
    $buffer = '';

    foreach($files as $file) {
        $buffer .= file_get_contents(__DIR__ . '/' . $file);
    }

    return $buffer;
}

$js = concatenateFiles([
  'core.min.js', 
  'promise.js', 
  'welcome.js',
  'imagesloaded.js',
  'cropper.js',
  'translate.js',
  'custom.js',
  'masonry.js',
]);

$output = \JShrink\Minifier::minify($js);
echo $output; 

Then I call this php file in my index page footer:

<script type="text/javascript" src="<? echo $url ?>/js/js.php"></script>

It is not being cached.

I modify my JS codes daily and I don't like to keep combining them manually, but also I need a way to get the echoed JS code cached, only that code and not all php files on the server.

How can I do this, and how would the cache purge process be?

Thanks in advance.

2 Answers 2

1

In theory, you need to use a header("...") with proper expiration. In practice, that's not working properly. You can spend your life googling for proper examples of "Cache-Control" and "Expires:" and none of what you find will work. So I suggest you to read this:

https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching

ETags are the modern solution to tell the browser when your resource has changed - or not.

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

2 Comments

You made my day man, thanks. I followed your note and found this great answer, I hope it helps someone: stackoverflow.com/questions/13197479/…
Glad to hear that :) Have a nice optimized data transfer!
0

If the cache file doesnt exist or if any of the file modification timestamps is later then the cache, render it, then safe it to the cache, then echo the cache or the rendered result.

Comments

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.