Question

After 2 days of work, we got success with the minification and combine multiple js files in one file.

In our framework, first we create the minified file, if not exist. and from PHP/template file we are loading same file in <script src=''></script> tag.

But each time when we are requesting for the same js file, each time it gets downloaded by the browser (As it shows 200 Ok status) but we are expecting to be 304 (Not modified) as that file was requested before as well.

What we can do so that the file will be get cached by browser?

Edit 1 :

<?php
$content = NULL;
$jsFiles = array(..);//all files
foreach($jsFiles as $file) {
$content .= file_get_contents($file);
}

$minifiedContents = jsMinify($content);
file_put_contents($MinifiedJsFilePath, $minifiedContents);//minified.js

?>

<html>
<head>
<title>Minification</title>
<script src="minified.js"></script>
</head>
</html>
Was it helpful?

Solution

Your server needs to support the If-Modified-Since request header (and/or other conditional get headers). These headers are sent by the web browser with every (conditional) get request.

A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s)

In essence, your server needs to:

  1. Check the presence of these fields in the request header.
  2. Use these conditions to determine if to serve the page or return an HTTP 304 response.

A search in google will give you numerous PHP examples. Like this one.

Edit:

Separate server logic from client logic and markup.
You could do something like this:

Server:

Create a PHP script (let's name it getjs.php) which returns the minified JS content, or 304 response if nothing has changed:

<?php

if (/*Determine if need to return 304*/){
    header('HTTP/1.0 304 Not Modified');
    exit;
}

$content = NULL;
$jsFiles = array();//all files
foreach($jsFiles as $file) {
    $content .= file_get_contents($file);
}

$minifiedContents = jsMinify($content);

header("content-type: application/javascript");
echo $minifiedContents;

?>

Client:

<script src="getjs.php"></script>

OTHER TIPS

Why not to set status code manually in PHP?

<?
// ...

if ($file_not_modified) {
    http_response_code(304);
} 

//...
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top