Using AJAX / jQuery to refresh an image

前端 未结 4 1275
生来不讨喜
生来不讨喜 2020-12-06 15:04

This is probably a simple question but I am stumped and just don\'t know where to start.

I have a PHP script (image_feed.php) that returns a URL to an image. Every t

4条回答
  •  不知归路
    2020-12-06 15:40

    $(document).ready(function() {
        var $img = $('#image1');
        setInterval(function() {
            $.get('image_feed.php?CAMERA_URI=', function(data) {
                var $loader = $(document.createElement('img'));
                $loader.one('load', function() {
                    $img.attr('src', $loader.attr('src'));
                });
                $loader.attr('src', data);
                if($loader.complete) {
                    $loader.trigger('load');
                }
            });
        }, 5000);
    });
    

    Untested. Code above should load the new image in the background and then set the src attribute of the old image on load.

    The event handler for load will be executed only once. The .complete check is necessary for browsers that may have cached the image to be loaded. In such cases, these browsers may or may not trigger the load event.

提交回复
热议问题