简体   繁体   English

忽略脚本错误并继续加载页面

[英]Ignore script error and carry on loading page

I have a module in NodeJS (SocketIO), and clients load it via: 我在NodeJS(SocketIO)中有一个模块,客户端通过以下方式加载它:

<script type="text/javascript" src="<?PHP echo $socketServer; ?>socket.io/socket.io.js"></script>
    <script type="text/javascript">
      var socket = io.connect('http://192.168.0.15:8123');
    </script>

The problem is, is if the Node server is offline the script will break and the rest of the page will stop loading. 问题是,如果节点服务器脱机,脚本将中断,页面的其余部分将停止加载。

My app does not depend on Node to function properly, so I need everything to carry on loading whether or not Node is working. 我的应用程序不依赖于Node才能正常运行,因此无论Node是否正常运行,我都需要进行加载。

How can this be done? 如何才能做到这一点?

If socket.io script is optional, then you can implement lazy loading of script: 如果socket.io脚本是可选的,则可以实现脚本的延迟加载:

function lazyLoad(url, callback) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;

  script.onload = script.onreadystatechange = function() {
    if (script.loaded == false && (!this.readyState || this.readyState == 'complete')) {
      script.loaded = true;

      console.log('script loaded');
      callback();
    }
  };
  script.onerror = function() {
    console.log('error loading');
  }

  document.body.appendChild(script);
}

Then use it that way: 然后以这种方式使用它:

lazyLoad('/socket.io/socket.io.js', function() {
  try {
    var socket = io.connect('http://192.168.0.15:8123');
  } catch(e) {
    console.log(e);
  }
});

BTW, make sure you load and connect to socket.io on the same server, otherwise you will face issues with CORS and many security limitations based on different browsers security policies. 顺便说一句,请确保在同一服务器上加载并连接到socket.io,否则您将面临CORS问题以及基于不同浏览器安全策略的许多安全限制。

If you don't care at all about result of io.connect just place into try/catch statement and ignore the exception 如果您根本不关心io.connect结果,只需将其放在try / catch语句中,然后忽略该异常

<script type="text/javascript">
try {
      var socket = io.connect('http://192.168.0.15:8123');
} catch (e) {
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM