嵌入式PHP在HTML中慢速加载页面

I've a php script that gets tweets and echo them. The problem is the page takes some time to load.

Is there a way I could first load the page as it is, and when the tweets are ready, edit the page with the tweets?

Try Chirp.js, that's a really good library for loading Tweets with Javascript: http://lab.rog.ie/chirp/

I would go with AJAX, but an alternative would be to create an iframe which uses your twitter code and mark up file as its source

document.readyState property can be used to check if your page is loaded.

if(document.readyState === "complete") {
  //Already loaded!
}
else {
      //Add onload or DOMContentLoaded event listeners here: for example,
      window.addEventListener("onload", function () {

          /*   you may use ajax to get the tweet contents like this. */
      xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                }
              }
            xmlhttp.open("GET","tweetsPage.php",true);
            xmlhttp.send();

    }, false);

}

Sounds like PHP isn't really required. I'd go for a a javascript option like Chirp.js; as mentioned above.

However, if you're dead set on using PHP (perhaps you have additional functionality built in to the script?) I would go for the jQuery/AJAX route.

  • Have a placeholder div - set the CSS to ensure that it wont break the layout, and have a loading image or similar.
  • Run a $.AJAX() request to the PHP script, and then directly output the results of the request into the placeholder div

This should minimise any layout issues whilst still providing a consistent user experience whilst the script is loading. As $.AJAX() is asynch - no functionality on the page will be blocked, as opposed to the current issue where the page isn't even displaying! Naturally, the only downside is that the tweets will still take time to load.

Perhaps if you posted up your PHP script or told us about your server set-up we may be able to troubleshoot the real issue though - why the PHP script is taking so long to execute? This is probably the most interesting part of the problem, as you may be doing something incorrectly which could lead to problems later on in production.