Reputation: 660
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.
Upvotes: 3
Views: 412
Reputation: 1625
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.
Upvotes: 1
Reputation: 4329
i have always used cache-control with the max-age
directive.
header('Cache-Control: max-age=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
but i also agree with the previous comment. if your db calls are really that expensive, think about offsetting how often those calls are made. for instance, if you wanted to update your db cache once every day, i'd do something like this.
you can optionally you can have IIS run the update script via the task scheduler, then your script that makes the js can never do the age check, just read from the cache.
Upvotes: 1
Reputation: 581
If the database queries are that expensive, the simplest way is to write the whole generated output into a file and just output the file instead of querying the db every time the page is loaded. All you have to do then is to delete / update the file when the database changes.
You should also consider looking into memory caches and try to optimize your queries if possible.
Upvotes: 1