Reputation: 1442
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 this one include with ajax? I don't want the ajax to be triggered by a button click I just want it to load up the include as the page is loading so that if you look at my example below 'Some more html content' would be displayed whilst the inlude.php is still loading in.
<html>
<head>
</head>
<body>
Some html content
<script>
Ajax load 'include.php';
</script>
Some more html content
</body>
</html>
Upvotes: 3
Views: 33940
Reputation: 1002
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:
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.
Upvotes: 0
Reputation: 176
use jquery , load php after DOM ready (before they render)
<div id="include"></div>
$(function(){
$("#include").load("include.php");
});
Upvotes: 1
Reputation: 787
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:
<div id="content"></div>
<script>
$(document).ready(function() {
$("#content").load("/yourpath/include.php");
});
</script>
Upvotes: 5