是否有非ajax方式重复轮询外部js文件?

would really appreciate any help with this JS question.
Have been experimenting for an hour or so now and haven't bumped into anything that does the trick.


Current Setup

  • Website 1: the 'content' site. This site displays different content depending on whether a user is logged into website 2 or not. I'm using a script tag in the head with the src set to a PHP file located on website 2.
  • Website 2: the 'user management' site. This uses PHP to output in a 'javascript' file whether a user is logged in (i.e. as a js var).


Currently this setup works fine for checking whether a user is logged into website 2 system when a user loads the page on website 1.

However, rather than a once-off check, I'm wanting the PHP file on website 2 to be polled every 2 seconds to see if the loggedin status has changed.

Is there a way to do this in vanilla javascript? (i.e. without ajax or jq - I'm trying to keep the whole system small and known).

If it's relevant, a friend suggested putting a randomly generated variable at the end of the PHP file name to prevent caching. (He didn't know how it could be repeatedly polled though!)

I suppose you could create an interval function changing the src property of a script element in your page?

setInterval(
  function(){
    myscript.src = '/urltophp?'+someRandomKey;
  }, 2000);

Where someRandomKey prevents the script being cached in the browser. A script tag can have an id, so it's retrievable using document.getElementById

To create a random key this may help:

function randomKey(iLen) {
  var sKey = ''
  , isKey = ''
  , i = 0
  , aRanges = ['48,9', '65,25', '97,25'];
  iLen = !iLen ? 4 : iLen;
  while (i < iLen) {
    var aRange = String(aRanges[Math.round(Math.random() * 2)]).split(',');
    isKey += String(aRanges[Math.round(Math.random() * 2)]) + ',';
    sKey += String.fromCharCode(Math.round(parseInt(aRange[0], 10) +
        (Math.random() * parseInt(aRange[1], 10))));
    i++;
  }
  return sKey;
}
setInterval(function(){


    $('#divtoloadcontentin').load('urlofscript' + '&nocache=' + Math.random()*Math.random());

}, 5000);

The only reason the divloadcontentin is their is because you could load in a php date() function to show users how up to date the page is.