Search code examples
javascripthtmlasynchronousesp8266

Anyone knows what I could do to this javascript code to make it more reliable?


I don't really know all that much about javascript at all yet, I just recently started learning it bc I needed it for a microcontroller project where we needed to use an MCU with network capabilities so apart from making the mcu code I was tasked with creating the web pages it would provide to the user. In one instance I made a section where the user would be able to see all (actually most, at least the ones I thought of importance to them) the parameters for the Led matrix that they get to set up. The problem is that, in order to load the parameters I used a method that I believe isn't really efficient, and the fact that I still don't know much about js doesn't help it. Does any of this seem to have a much easier solution to you?

<div class="row">
  <div id="column1" class="column">
  </div>

  <div class="column middle">
    <h3 style="color: rgb(187, 187, 187);">Parámetros guardados: </h3>
    <div class="guardado">
    <p >Mensaje guardado inicial: <span id="mensaje"></span></p>
    <p >Brillo guardado: <span id="brightness"></span></p>
    <p >Velocidad guardada: <span id="speed"></span></p>
    <p >Alineación: <span id="text_align"></span></p>
    <p >Modo operando: <span id="MODO"></span></p>
    <p >Tiempo entre mensajes (M2): <span id="TIME"></span></p>
    <p >Efecto (M1): <span id="EM1"></span></p>
    <p >Efecto inicio (M2): <span id="E1M2"></span></p>
    <p >Efecto salida (M2): <span id="E2M2"></span></p>
</div>
</div>
  
 <script>
    //Load parameters
    var xhttp = new XMLHttpRequest();           //Message
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("mensaje").innerHTML = this.responseText;
      }
    };
    xhttp.open("GET", "/mensaje", true);
    xhttp.send();

    var xhttp = new XMLHttpRequest();           //Brightness
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("brightness").innerHTML = this.responseText;
      }
    };
    xhttp.open("GET", "/brillo_guardado.txt", true);
    xhttp.send();

    var xhttp = new XMLHttpRequest();           //Speed
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("speed").innerHTML = this.responseText;
        document.getElementById("speed").innerHTML += "%";
      }
    };
    xhttp.open("GET", "/velocidad_guardado.txt", true);
    xhttp.send();   

    var xhttp = new XMLHttpRequest();           //MODE
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("MODO").innerHTML = this.responseText;
      }
    };
    xhttp.open("GET", "/modo_guardado.txt", true);
    xhttp.send();   

    var xhttp = new XMLHttpRequest();           //Text alignment
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("text_align").innerHTML = this.responseText;
      }
    };
    xhttp.open("GET", "/alineacion_guardado.txt", true);
    xhttp.send();

    var xhttp = new XMLHttpRequest();         //var initial_time
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("TIME").innerHTML = this.response;
        document.getElementById("TIME").innerHTML += "ms";
      }
    };
    xhttp.open("GET", "/tiempo_guardado.txt");
    xhttp.send();

    var xhttp = new XMLHttpRequest();         //EFFECT MODE 1
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("EM1").innerHTML = this.response;
      }
    };
    xhttp.open("GET", "/effecto_modo1_guardado.txt");
    xhttp.send();

    var xhttp = new XMLHttpRequest();         //EFFECT 1 MODE 2
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("E1M2").innerHTML = this.response;
      }
    };
    xhttp.open("GET", "/effecto1_m2_guardado.txt");
    xhttp.send();
    
    var xhttp = new XMLHttpRequest();         //EFFECT 2 MODE 2
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("E2M2").innerHTML = this.response;
      }
    };
    xhttp.open("GET", "/effecto2_m2_guardado.txt");
    xhttp.send();
    
</script> 

This is what it looks like after loading

The page is going to be asking the mcu for several parameters it has stored and then it'll display them.


Solution

  • The code can be cleaned up a lot:

    function loadText(elementId, url, suffix = ""){
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById(elementId).innerHTML = this.responseText + suffix;
            }
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    }
    
    //Load parameters
    loadText("mensaje",    "/mensaje");
    loadText("brightness", "/brillo_guardado.txt");
    loadText("speed",      "/velocidad_guardado.txt", "%");
    loadText("MODO",       "/modo_guardado.txt");
    loadText("text_align", "/alineacion_guardado.txt");
    loadText("TIME",       "/tiempo_guardado.txt", "ms");
    loadText("EM1",        "/effecto_modo1_guardado.txt");
    loadText("E1M2",       "/effecto1_m2_guardado.txt");
    loadText("E2M2",       "/effecto2_m2_guardado.txt");
    

    When you're repeating code like that, put it into a function.

    Other than that, there's not much you can do to make it faster, as you're loading every individual string from a separate url.

    Instead of the old-fashioned XMLHttpRequest, you can also make use of the fetch API:

    function loadText(elementId, url, suffix = ""){
        fetch(url).then((response) => {
            document.getElementById(elementId).innerHTML = response + suffix;
        });
    }