Conditional connection to LiveView socket

Hello! First post in the forums! But have been reading for years.

We are thinking about implementing LiveView in a Phoenix Application that has been running for some years now. It’s an awesome technology, but we want to understand properly the implications it will bring to our App.

We are going to start transforming some old templates into LiveView and see how they work. We are afraid that we are going to force an unnecessary connection to the Websocket, and that will probably increase the impact on our server, as we will need a double connection. One for the first rendering, and the second one for the socket. We already have a lot of visitors, and we think it would avoid a lot of performance problems.

We are trying to make the socket connection conditional. I mean, connecting after a certain user action, for example, a click on a checkbox.

Below is an example of what we are trying to accomplish. (Yes, we are still using jQuery).

const SocketHooks = function (target) {
  return {
    mounted() {
      let tag = $(target).prop("tagName")
      if ((tag == "INPUT" || tag == "LABEL")) {
        $(target).click();
      }
    }
  }
}

$("#facets-list").on("click", (e) => {
  const PrepareHooks = SocketHooks($(e.target));
  let hooks = { PrepareHooks };
  let liveSocket = new LiveSocket("/live", Socket, { hooks: hooks })
  
  liveSocket.connect();
  $("#facets-list").off("click")
})

Using the socket hooks, we get the original click when the socket is not yet connected, we establish the connection, we simulate the click after an amount of time, and we remove the click event so it doesn’t connect again on the second click. We would show a loader meanwhile.

Our questions would be:

  • Is it necessary? I mean, do you think the impact on our server we would be saving with it is worth it?
  • If the previous answer is yes: what do you think about this approach?
  • Any other ideas to handle the socket connection?

Thank you in advance!

1 Like