Right now i use this code to get a random text in my web-application.
$(document).ready(function() {
$("#refresh").click(function(evt) {
$("#content").load("load.php")
evt.preventDefault();
})
})
Load.php is loading a random text from the database. Is their anything i can do to speedup this session. It would be great if someone also have and idea how the webbapplication could be used without 3G and WiFi.
You can add to your php code a cache function.
When you load the random text, write it into /cache/mytext.cache
and write an unix timestamp into /cache/mytext.info
Now, on top of your php script, read /cache/mytext.info
and check if it's too old, if so, generate a new text and update the timestamp of mytext.info, else, load as text the content of /cache/mytext.cache
// Fetch the timestamp saved in /cache/mytext.info
$cachedate = file_get_contents('./cache/mytext.info', true);
// If timestamp + _× seconds_ is < of current time
if(($cachedate + 3600) < time()) {
// Fetch your new random text and store into $mytext
// for example: $mytext = getrandomtext();
// Write into /cache/mytext.cache your new random text
$fp = fopen('./cache/mytext.cache', 'w');
fwrite($fp, $mytext);
fclose($fp);
// Update timestamp written into /cache/mytext.info
$fp = fopen('./cache/mytext.info', 'w');
fwrite($fp, time());
fclose($fp);
}
// Your random text is into $mytext
$mytext = file_get_contents('./cache/mytext.cache', true);
// Print it with echo
echo $mytext;
Cache a single request in the browser and use jQuery's really useful, and much underused, Deferreds http://api.jquery.com/category/deferred-object/, of which an ajax call is an instance, to make sure it only gets loaded once the content has arrived
$(document).ready(function() {
var nextContent = $.get('/load.php');//preload the result of the first random text request
var clicked = false;
$("#refresh").click(function(evt) {
if (!clicked) { // prevent sending loads of requests if user reclicks impatiently
clicked = true;
nextContent.done(function (response) {
console.log('yay')
$("#content").html(response); // print the text
clicked = false;
nextContent = $.get('/load.php'); //preload the next request
})
}
evt.preventDefault();
});
})