开发者

Javascript: Force a reload from the server, how?

I just found a snippet of code to开发者_Go百科day as I need to refresh a page of mine so that a PHP script can run again to show new results from the DB every minute or so.

if (document.images)
    setTimeout('location.reload(true)',1000*60*15); // forces a reload from the server
else
    setTimeout('location.href = location.href',1000*60*15);  // just reloads the page

Whats the difference between the two? I mean do they not reload the page? How can the JS code force a reload from the server?

Thanks all


The snippet will try to make a full page reload, if there are images on the page, otherwise it just make a redirect to the same page itself.

Using location.reload(true);, the true argument causes the page to always be reloaded from the server.

But that condition is always true, since document.images is an HTMLCollection, and it will never evaluate to false, even if there are no images on the page, the only values that evaluate to false in a boolean expression are null, undefined, 0, NaN, an empty string, and of course false.

If you want to make that condition work, you should check the length property of document.images, the length property is numeric and that means that it will evaluate to false only when its value is 0:

if (document.images.length) {
    setTimeout(function () {
        location.reload(true); // forces a reload from the server
    }, 1000*60*15); 
} else {
    setTimeout(function () {
        location.href = location.href;
    }, 1000*60*15);  // just reloads the page
}

Notice also that I'm now using function expressions instead of strings as the first argument of setTimeout, if strings are used the code will be evaluated at runtime (equivalent to a eval call) and that is not really considered as a good practice.


i think the location.reload(true) will force the page reload from the server, the second example will reload the page but it will access the browser cache if it exists (and it probably does).

here's a little more on the location.reload() method http://www.devguru.com/Technologies/Ecmascript/Quickref/reload.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜