0

I'm using the below script to check for internet connection by downloading the image test.png. The issue I'm having is that it will only download the image once. This means, if there was internet connection when the page was first loaded it will display "Online" - however, if I disconnect the network cable, it won't say "Offline", as it should.

Basically, once downloaded, the readyState will always be 'complete' - However, I would like to perform the test again and again.

<script type="text/javascript">
setInterval('checkimage()', 1000);

function checkimage() {
    var imgTmp = new Image();
    imgTmp.src = 'test.png';
    if (imgTmp.readyState == 'complete') {
        document.getElementById('div1').innerHTML = "<font size=15 face=ariel color=green>Online</font>";
    } else {
        document.getElementById('div1').innerHTML = "<font size=15 face=ariel color=red>Offline</font>";
    }
}
</script>

Any help would be greatly appreciated!

4

2 回答 2

2

I'm doubtful about the whole solution but if you want to force a download, that is avoid the cache, you may replace

imgTmp.src = 'test.png';

with

imgTmp.src = 'test.png?t='+(new Date().getTime());
于 2013-02-07T11:56:26.730 回答
1

The problem with your solution is, that you're checking the readyState immediately after setting the source. Use the load and error events instead.

function checkimage() {
    var imgTmp = new Image();
    imgTmp.onload = function() {
        printState("Online");
    };
    imgTmp.onerror = function() {
        printState("Offline");
    };
    imgTmp.src = "test.png?_=" + (+new Date());
}

function printState(state) {
    document.getElementById("div1").innerHTML = "<span style=\"font-size:15;font-face:'Arial'; color:green\">" + state + "</span>";
    setTimeout(checkimage, 5000);
}

And don't use strings as first parameter for setTimeout and setInterval

于 2013-02-07T12:12:31.620 回答