title: Run websocket in web worker or service worker - javascript
body: <p>I have 9 websocket connections from different sites working to update the DOM with data. Currently I am connecting to all and listening to all websockets and updating the data with a function call.</p>
  
  <p>The issue I'm facing is that there are many websocket connections and there are memory and CPU usage issues. How can I use either service workers and web workers to optimize so many websocket connections?</p>
  
  <pre class="lang-js prettyprint-override"><code>async function appendGatePublicTickersData(e) {
    if (e.event == "update" &amp;&amp; e.result[0].contract == "BTC_USD") {
      if ('total_size' in e.result[0]) {
        $(".gate-btc-open-interest").html(commaNumber(e.result[0].total_size))
        if ('last' in e.result[0]) {
          $(".gate-btc-open-value").html(commaNumber(customFixedRounding((e.result[0].total_size / e.result[0].last), 4)))
        }
      }
  
      if ('volume_24h_usd' in e.result[0]) {
        $(".gate-btc-24-volume").html(commaNumber(e.result[0].volume_24h_usd))
      }
  
      if ('volume_24h_btc' in e.result[0]) {
        $(".gate-btc-24-turnover").html(commaNumber(e.result[0].volume_24h_btc))
      }
  
      if ('funding_rate' in e.result[0]) {
        var fundingRateBtcGate = customFixedRounding(e.result[0].funding_rate * 100, 4)
        $(".public-gate-btc-funding").html(fundingRateBtcGate)
      }
  
      if ('funding_rate_indicative' in e.result[0]) {
        var predictedRateBtcGate = customFixedRounding(e.result[0].funding_rate_indicative * 100, 4)
        $(".public-gate-btc-predicted").html(predictedRateBtcGate)
      }
    }
  }
  
  var pubGateWs = new WebSocket("wss://fx-ws.gateio.ws/v4/ws/btc");
  
  pubGateWs.addEventListener("open", function() {
    pubGateWs.send(JSON.stringify({
      "time": 123456,
      "channel": "futures.tickers",
      "event": "subscribe",
      "payload": ["BTC_USD", "ETH_USD"]
    }))
  });
  
  pubGateWs.addEventListener("message", function(e) {
    e = JSON.parse(e.data)
    appendGatePublicTickersData(e)
  });
  
  pubGateWs.addEventListener("close", function() {});
  </code></pre>