1

现在我使用此代码在我的网络应用程序中获取随机文本。

 $(document).ready(function() {
      $("#refresh").click(function(evt) {
         $("#content").load("load.php")
         evt.preventDefault();
      })
    })

Load.php 正在从数据库中加载随机文本。我能做些什么来加快这次会议吗?如果有人也知道如何在没有 3G 和 WiFi 的情况下使用 webb 应用程序,那就太好了。

4

2 回答 2

0

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;
于 2013-02-12T12:38:39.200 回答
0

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();
  });
})
于 2013-02-12T13:00:23.630 回答