How to load php to a page using ajax during page load

I have a php include that takes a while because PHP has to receive a lot of data. I don't want to slow down the loading of the entire web page waiting for this, so how can I load this attribute using ajax? I dont want ajax to be called on button click. I just want it to load the include when the page is loaded, so if you look at my example below some more html content will be displayed at the time of include. php is still loading.

<html>
<head>
</head>
<body>
    Some html content
    <script>
        Ajax load 'include.php';
     </script>
    Some more html content
</body>
</html>

      

+2


source to share


3 answers


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

For example:



<div id="content"></div>

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

      

+2


source


use jquery, load php after DOM is ready (before they are rendered)



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

      

+1


source


If you are not using jQuery, you can trigger the AJAX function using document.onload. I've never tried this, to be fair, as most PHP is lightning fast and I will worry about what happens if the page is only partially loaded. You can use document.ready to avoid this, but then you just wait for the page to load. Remember that you have limited connections for each browser to the server over HTTP, so you may find that this doesn't speed things up in the end.

I use some pretty technical pages and sometimes they load in under 0.06 seconds, although they are usually faster. It's on a very cheap and otherwise poor server with extremely scarce resources. Users cannot perceive this as a delay as it takes much longer to load the content than PHP takes.

Ask yourself:

  • List Item Why is my code taking so long to load?
  • List Item Do I need all this code in an include?
  • List Item Is there a better way?
  • List item. Should I remove infrequently used code for splitting (or use the batch class load facility in PHP)?

It might be better to simplify the code to make it run faster. If you are not going to serve all the data you receive, you may not need to take it at all. If you are going to serve it, this is something that will take time, not processing.

0


source







All Articles