I just found a snippet of code today 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);, thetrueargument causes the page to always be reloaded from the server.But that condition is always
true, sincedocument.imagesis an HTMLCollection, and it will never evaluate tofalse, even if there are no images on the page, the only values that evaluate tofalsein a boolean expression arenull,undefined,0,NaN, an empty string, and of coursefalse.If you want to make that condition work, you should check the
lengthproperty ofdocument.images, thelengthproperty is numeric and that means that it will evaluate tofalseonly when its value is0: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 aevalcall) and that is not really considered as a good practice.