开发者

Javascript: Detect an image's loading status, and only swap out the old image when the new one is 'loaded'?

i call on a PHP script that generates graph images for me, however, it takes a few seconds. Is there a way to detect when it has finished loading, on the user side, and only swap it with the old image when the php script has finished and the image is ready?

here is the Javascript function i use to call the PHP script:

EDIT (CODE UPDATED)

function loadGraph(self,graph,varID) {
    var img = new Image();

    img.onload = function() {
        $(self).parents().parents().siblings(".graph_container").empty().append(img);
    };

    img.src = 'drawGraph.php?type=journey_report&graph=' + graph +
        (varID != null ? '&amp;varID=' + varID : '') + '&amp;companyID=<?php echo $_SESSION['companyID'] ?>';   
}

and here is the graph container and the link that uses that function:

<div class="graph_container">
                        <img src="drawGraph.php?type=journey_report&graph=outOfDate_vs_upToDate&companyID=<?php
                            echo $_SESSION['companyI开发者_如何转开发D'] ?>" />
                    </div>

                    <div class="reportItemWrapper">
                        <div class="reportItem"><a href="#" onclick="loadGraph(this,'outOfDate_vs_upToDate'); return false"><b>Total</b></a></div>

thanks!


Create an Image object and set its "onload" handler to a function that does what you do in that first block of code. Then set its "src" attribute to your URL.

var img = new Image();
img.onload = function() {
  // that jQuery stuff
};
img.src = "drawGraph.php?type=journey_report ...";

Now that'll only work if the URL is cacheable. If not, then you could re-work that jQuery code so that you just stuff the Image element into the DOM.

$(self).parents().parents().siblings(".graph_container").empty().append(img);

(You'd still do that in the onload handler.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜