Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching a php generated javascript page

I have a php generated javascript page that is creating an array from a database and is absolutely murdering my page load time. The page has a php extension and is currently using a header to mark its content-type as application/javascript.

I found a possible solution online, but it doesn't seem to be doing much to speed up my page's load time. The header code of my file right now is this:

header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * 3;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr); 
header("Content-type: application/javascript");

Is there anything special I need to be doing to cache the file so I don't have it constantly trying to load these database calls? I'm using IIS 7.5 and PHP 5.3.13.

like image 814
gdawgrancid Avatar asked Jan 30 '26 11:01

gdawgrancid


1 Answers

It seems to me that you are hardcoding the array in tags. If the array is really big, the browser have to load more bytes.

Consider using AJAX in conjunction with JSON. Use forexample jQuery to load the data from another script. E.g. api.php?req=getBigArray. And jQuery "success" callback to run logic when array is loaded. This means that two http requests will be done, but it will load your page at once.

Serverside:

<?php //api.php
switch($_GET['req']){
 case "getBigArray": 
    $arrayFromDatabase = array( /* Load from db ... */ );
    echo json_encode($arrayFromDatabase); 
 break;
}

Client:

$(document).ready(function(){
    $.getJSON('api.php?req=getBigArray', function(data) {
        console.log(data); // Use data in some way.
    });
});

This also decouples logic from serverside / frontend.

You can also look at memcache/apc if you want to cache results at the backend. Really simple API, but requires extra software installed on the serverside.

like image 191
Petter Kjelkenes Avatar answered Feb 02 '26 01:02

Petter Kjelkenes