Skip to content Skip to sidebar Skip to footer

How Do I Load A Php Include Into A Page With Ajax Whilst The Page Is Loading

I have a php include which takes awhile to load because PHP has to fetch a lot of data. I don't want to slow the whole webpage loading waiting for this include so how can I load th

Solution 1:

If you're using jQuery, you could you use one of their ajax calls to load your html from include.php. For example you could use the load() function.

For example:

<divid="content"></div><script>
$(document).ready(function() {
    $("#content").load("/yourpath/include.php");
});
</script>

Solution 2:

use jquery , load php after DOM ready (before they render)

<div id="include"></div>
$(function(){
    $("#include").load("include.php");
});

Solution 3:

If you are not using jQuery, you could trigger your AJAX function using document.onload. I have never tried this to be fair as most PHP is lightning fast and I'd worry about what would happen if the page only partially loaded. You could use document.ready to avoid this, but then you're just waiting for the page to load. Remember you have limited connections per browser per server by HTTP so you may find this does not speed anything up in the end.

I use some pretty technical pages and occasionally they take as long as 0.06 seconds to load though usually they are quicker. This on a very cheap and nasty server with extremely scant resources. Users cannot perceive this as a lag as it takes much longer to download the content than PHP takes to serve it.

Ask yourself:

  • List item Why is my code taking so long to load?
  • List item Do I need all that code in the include?
  • List item Is there a better way?
  • List item Should I remove infrequently used code to separate includes (or use the class batch loading facility in PHP)?

Perhaps it might be better to simplify your code so it runs faster. If you don't intend to serve all that data you are fetching, perhaps you don't need to fetch it at all. If you are going to serve it, that is what is going to take the time, not the processing.

Post a Comment for "How Do I Load A Php Include Into A Page With Ajax Whilst The Page Is Loading"