现在我使用此代码在web应用程序中获取随机文本。
$(document).ready(function() {
$("#refresh").click(function(evt) {
$("#content").load("load.php")
evt.preventDefault();
})
})
Load.php正在从数据库中加载一个随机文本。我能为他们做些什么来加快这次会议吗。如果有人也知道如何在没有3G和WiFi的情况下使用webba应用程序,那就太好了。
在浏览器中缓存单个请求,并使用jQuery的Deferredhttp://api.jquery.com/category/deferred-object/,其中ajax调用是一个实例,以确保只有在内容到达后才加载
$(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();
});
})
您可以在php代码中添加一个缓存函数。
加载随机文本时,将其写入/cache/mytext.cache
,并将unix时间戳写入/cache/mytext.info
现在,在php脚本的顶部,读取/cache/mytext.info
并检查它是否太旧,如果是,则生成一个新文本并更新mytext.info的时间戳,否则,将/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;