开发者

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

开发者 https://www.devze.com 2023-01-09 05:23 出处:网络
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

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

精彩评论

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

关注公众号