How to check if the php website has been fully loaded with JS

advertisements

So I have an index.php, where inside I have some Div's like this:

<div id="thisDiv">
    <?php ?>
<div>

and in another JS file, I have a divRefresh function like this:

function divRefresh(id, path){
    $(id).load(path, function(){
        functionToBeCalledWhenLoaded();
    });
}

where ID would be the id from the div, and PATH the path to where the php file is in the server.

My problem is that the load() function calls the functionToBeCalledWhenLoaded() before even my .php page was completelly loaded.

Solutions tried:
callback functions.
inline <script> call. (this solution worked with only some people)
jquery ready(),onload(),load()

How do I check if my php page was completelly loaded before calling a JS function?


It seems that the DOM is ready while the PHP server still sends data. Here you go some suggestions that may convince the browser to understand the situation. First, try to turn it off and on again. If it doesn't help:

Suggestion 1

Try to send header("Content-Length: ...") - it may convince the browser to wait until all data are sent. The ... is the byte size of the generated HTML, of course.

Suggestion 2

Try to use output buffering:

<?php ob_start();?>
<div id="thisDiv">
    <?php ?>
<div>
<?php ob_end_flush();?>

The server will wait until the html is fully generated and then it will send it to the client, so the last data would be ...</html>, after which the DOM will be ready and after that the JS load will launch. At least I hope so.

Suggestion 3

At the end of the php code which you put inside thisDiv, insert this line

<img src="pixel.gif" onload="functionToBeCalledWhenLoaded()">

Where the pixel.gif is some real 1px invisible image, so the function will launch after the php part is done. This could work when the DOM is ready and the relevant data are sent, while the browser waits for some more data.


Last, but not least, it could be some cache issue. As the last resort, you could use setTimeout(functionToBeCalledWhenLoaded,1000) to wait another second and hope that the page will be really ready after the delay. This would be a nice example of duct-tape antipattern, an act of sheer despair.