JSONP Long Polling always loading

2019-04-01 18:33发布

问题:

I'm doing long-polling with JSONP and firefox continually pops up the "Loading" spinner making the page seem like it hasn't finished loading. Is there a way to suppress this?

I've been told that the Orbited team has hacks for suppressing this, but looking through the Orbited.js code I cannot figure out what they are. Any help would be greatly appreciated.

回答1:

This is a simple fix.. All you have to do is start your polling request with a setTimeout..

Here is some code I use.. It uses jQuery, but I assume you can figure out what you need to and use your library to do the same.

<script type="text/javascript">
  function poll(){
    $.getJSON('/updates', function(json){
      //reconnect since we successfully received data and disconnected
      poll();

      //add something here to do whatever with the recieved data
    });
  }
  /*call the poll function after document has loaded with setTimeout
  if called before the document finishes loading completely it will
  cause a constant loading indication*/
  setTimeout(poll, 1);
</script>


回答2:

I don't have an answer, but I do have a suggested alternative. Someone else just asked a similar question and here's my answer.

Basically, if you have control of the server, the simplest solution is to use Cross-Origin Resource Sharing headers to OK cross-domain XMLHttpRequest and fall back to JSONP on old browsers.

I've provided a reasonably complete compatibility table (every userscript-capable browser) for CORS as part of the answer I linked to, as well as a more general one on Wikipedia.