电子应用程序在运行Javascript代码时停止呈现

时间:2018-10-15 02:16:12

标签: javascript node.js electron

我目前正在开发一个电子应用程序,该应用程序实质上是我控制的媒体服务器的DDNS启动器。基本上,它会检查Internet连接,获取服务器的当前IP,然后在系统的默认浏览器中将其打开。但是,我写的启动屏幕完全坏了。

每当我在系统上启动应用程序时(使用终端上的npm),它都会加载框架,但是图像会冻结在1/3点处加载。在HTML主页面底部的脚本执行完毕之前,它不会加载其余图像。

我对此有什么想念的吗?如果需要,我可以提供代码摘录。

编辑:

源代码摘录:

<script>
  function wait(ms) {
    var start = new Date().getTime();
    var end = start;
    while (end < start + ms) {
      end = new Date().getTime();
    }
  }

const isOnline = require('is-online');
const isReachable = require('is-reachable');
const {
  shell
} = require('electron');

window.onload = function() {
  // Main Script
  console.log('before');
  wait(3000);
  document.getElementById('progresstext').innerHTML = "Testing connection...";
  bar.animate(0.15); // Number from 0.0 to 1.0
  wait(250);
  var amIOnline = false;

  if (isOnline()) {
    amIOnline = true;
  }
  console.log("Internet Test Ran");

  if (!amIOnline) {
    document.getElementById('errortext').innerHTML = "ERROR: No internet connection. Check the internet connection.";
    document.getElementById('progresstext').innerHTML = "ERROR";
  }

  var isEmbyReachable = false;
  if (isReachable('******')) {
    isEmbyReachable = true;
    document.getElementById('progresstext').innerHTML = "Connection Test: Passed";
    //=> true
  }

  //Open Emby in the default browser
  if (amIOnline && isEmbyReachable) {
    shell.openExternal("*****");
  }
};

</script>

Pastebin链接到完整来源:https://pastebin.com/u1iZeSSK

谢谢

开发系统规格:macOS Mojave 10.14,最新稳定的电子版本

1 个答案:

答案 0 :(得分:0)

问题出在您的wait函数中,因为节点js是单线程的,所以您的等待函数阻塞了您的进程。您可以尝试以下代码。但我真的建议您看看如何在JavaScript中编写异步函数,并以setInterval和setTimeout作为开始。

但是暂时您可以尝试使用此代码。

window.onload = function () {
    // Main Script
    console.log('before');

    // wait 3 seconds
    setTimeout(function () {
        document.getElementById('progresstext').innerHTML = "Testing connection...";
        bar.animate(0.15); // Number from 0.0 to 1.0

        // wait 250 mills
        setTimeout(function () {
            var amIOnline = false;

            if (isOnline()) {
                amIOnline = true;
            }
            console.log("Internet Test Ran");

            if (!amIOnline) {
                document.getElementById('errortext').innerHTML = "ERROR: No internet connection. Check the internet connection.";
                document.getElementById('progresstext').innerHTML = "ERROR";
            }

            var isEmbyReachable = false;
            if (isReachable('******')) {
                isEmbyReachable = true;
                document.getElementById('progresstext').innerHTML = "Connection Test: Passed";
                //=> true
            }

            //Open Emby in the default browser
            if (amIOnline && isEmbyReachable) {
                shell.openExternal("*****");
            }
        }, 250)
    }, 3000)


};

您可能不会在JavaScript中等待一段时间或任何其他阻塞循环,因为它会阻塞所有其他执行,包括页面渲染。