1

I have been searching for what happens with javascript code when html page is rendered.

In my html page I have script that does (let say) two things. One is to open socket to Node.js server and listen for event user-list and the other task is to register event for button click.

First I tried like this:

   var socket = io.connect(window.location.href);
   socket.on("user-list", (data) => {
    console.log("On no problem: " + JSON.stringify(data))
    let str = "";
    for(let i = 0; i < data.length; i++) {
     str += "Name: " + data[i].name + " Age: " + data[i].age + " | ";
    }
    $("#private").text(str)
   })
   
   $("#submit-btn").click(function() {
    let userName = $("#username").val(),
     age = $("#age").val();
    if( isNaN(age) ){
     console.log("Age is NaN")
     alert("Age must be a number!")
     return;
    }
    $.post("user-data", {username: userName, age: age}, function(result) {
     console.log(result);
    })
   })

But the button didn't work when clicked. Although, the socket connection worked well.

Then I tried to wrap the button click event registration in $(document).ready(function() {...}). like this:

   var socket = io.connect(window.location.href);
   socket.on("user-list", (data) => {
    console.log("On no problem: " + JSON.stringify(data))
    let str = "";
    for(let i = 0; i < data.length; i++) {
     str += "Name: " + data[i].name + " Age: " + data[i].age + " | ";
    }
    $("#private").text(str)
   })
   
   $(document).ready(function() {
    $("#submit-btn").click(function() {
     let userName = $("#username").val(),
      age = $("#age").val();
     if( isNaN(age) ){
      console.log("Age is NaN")
      alert("Age must be a number!")
      return;
     }
     $.post("user-data", {username: userName, age: age}, function(result) {
      console.log(result);
     })
    })
   })

Now it works. I know that $(document).ready(function() is evoked when the document is loaded, but why isn't it working without that function?

And the other question is: Why the socket is still working although not wrapped by $(document).ready(function()?

In other words, why $("#submit-btn").click(function().... need $(document).ready(function()..... in order to work?

Hairi
  • 3,318
  • 2
  • 29
  • 68

1 Answers1

0

Javascript gets execute the second the browser discovers it in the HTML-page. so your socket-connections gets initializied the moment your browser discovers the code. however, the button needs a html-object (button-tag) to be present to get initialized. if your javscript-code is in the head-section of your page, the button is most likely unknown for the script to get executed. to fix that. you could move your javascript to the bottom of your page.

wayneOS
  • 1,427
  • 1
  • 14
  • 20