3

I'm trying to develop something in real time which in this case, I'm using socketio for nodejs. Although everything else is working fine, my main issue now is that my program loads the javascript first before the HTML, which therefore means that the output at start is just empty.

In my code, the javascript calls everything else in the database and is concatenated by tags where in it is later thrown in the html.

Here is my code in html:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <table>
    <tr>
      <td>
        <table id="output" border=1>
          <thead id="headers">
            <th>Name</th>
            <th>Address</th>
            <th>Number</th>
          </thead>
          <tbody id="online">
          </tbody>
        </table>
      </td>
      <td>
        <table id="output" border=1>
          <thead id="headers">
            <th>Name</th>
            <th>Address</th>
            <th>Number</th>
          </thead>
          <tbody id="offline">
          </tbody>
        </table>
      </td>
    </tr>
  </table>
  <script src="/chat.js"></script>
</body>
</html>

And here is the javascript:

var online = document.getElementById('online'),
  offline = document.getElementById('offline');

socket.on('user joined', function(data) {
  online.innerHTML = "";
  for (var ctr = 0; ctr < data.length; ctr++) {
    online.innerHTML += '<td>' + data[ctr].name + '</td>' +
      '<td>' + data[ctr].address + '</td>' +
      '<td>' + data[ctr].number + '</td>';
  }
});

socket.on('user left', function(data) {
  offline.innerHTML = "";
  for (var ctr = 0; ctr < data.length; ctr++) {
    offline.innerHTML += '<td>' + data[ctr].name + '</td>' +
      '<td>' + data[ctr].address + '</td>' +
      '<td>' + data[ctr].number + '</td>';
  }
});

I've already searched this online however my case is different as I call the javascript file in the html, instead of having all the script with the html itself.

I've also read that having the javascript file be called after the html works, but apparently, I've done that (as seen in my codes) and still nothing.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
DayIsGreen
  • 255
  • 1
  • 4
  • 16
  • 1
    you can make the script only execute once the body has loaded? that would work for your use case – mast3rd3mon Jul 12 '18 at 08:33
  • I understand and that's what I'm trying to achieve, however I'm not all that familiar with almost any relation with the front end, needless to say the html (or even css). That said, can you please show me how to do so? – DayIsGreen Jul 12 '18 at 08:36
  • See this question: https://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load – Capricorn Jul 12 '18 at 08:37
  • @Capricorn - I tried following what was said on the link however it does not work for me. Maybe I'm doing it wrong? – DayIsGreen Jul 12 '18 at 08:46
  • Can you show us your browser console, just press F12 and choose the console tab. If there is an error logged there, that might help. – Lê Quang Bảo Jul 12 '18 at 08:50
  • It says, script is not defined. Do I have to insert "/chat.js" inside the parenthesis of ? – DayIsGreen Jul 12 '18 at 08:56

5 Answers5

4

You can use DOMContentLoaded:

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

Wrap your JavaScript code with:

document.addEventListener("DOMContentLoaded", function(event) { 
  // your code here
});
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    Someone please explain why this answer get down vote, it seem work for me, it just lacking some explaination. – Lê Quang Bảo Jul 12 '18 at 08:42
  • The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious. More on - https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded – AutoTester213 Jul 12 '18 at 08:44
  • I'm sorry but, can anyone show me how I will incorporate this with my codes that I have provided? I've tried but it didn't work for me. I assume I'm doing it wrong. – DayIsGreen Jul 12 '18 at 08:45
0

This might work:

<body onload="script();">

or

document.onload = function ...

or even

window.onload = function ...

Duplicate from JavaScript that executes after page load

Sir Catzilla
  • 321
  • 3
  • 18
0

Following Manums answer you can wrap your code using The DOMContentLoaded:

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious. More on DOMContentLoaded - here

Here is a code snippet that waits for the page to load and then opens the chat.js file.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <table>
    <tr>
      <td>
        <table id="output" border=1>
          <thead id="headers">
            <th>Name</th>
            <th>Address</th>
            <th>Number</th>
          </thead>
          <tbody id="online">
          </tbody>
        </table>
      </td>
      <td>
        <table id="output" border=1>
          <thead id="headers">
            <th>Name</th>
            <th>Address</th>
            <th>Number</th>
          </thead>
          <tbody id="offline">
          </tbody>
        </table>
      </td>
    </tr>
  </table>
  <script type="text/javascript">
  function downloadJSAtOnload() {
      var element = document.createElement("script");
      element.src = "/chat.js";
      document.body.appendChild(element);
  }

  if (window.addEventListener)
      window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
      window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>
</body>
</html>

UPDATE: You could load the script in the head tag and use the defer attribute

<script src="/chat.js" defer></script>

defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document.

Following the answer from here

AutoTester213
  • 2,714
  • 2
  • 24
  • 48
  • I appreciate your effort in answering my question, however it still doesn't work. Any substitute for this that might work? – DayIsGreen Jul 12 '18 at 08:52
  • @DayIsGreen have you tried to input the script direcly inside the html file? – AutoTester213 Jul 12 '18 at 09:01
  • Yes, and although it works, I prefer doing it this way (in my codes above) as I encounter issues when I put it directly with the html file, such as old records being concatenated with new ones, but that's a different issue so I wish to stick with what I have already done. – DayIsGreen Jul 12 '18 at 09:11
  • @DayIsGreen Another altenrative could be to use a onload function `function myFunction() { //code here to load your script }` `` or something simillar – AutoTester213 Jul 12 '18 at 09:19
  • This doesn't seem to produce any kind of error as per the console tab upon pressing F12, however it still doesn't work. I'm very certain there is data being sent upon load as I log evertime I load the page. – DayIsGreen Jul 12 '18 at 09:30
  • @DayIsGreen ok i have updated the answer once more, It's the last option that i know of hopefully it will help you – AutoTester213 Jul 12 '18 at 09:33
  • @DayIsGreen hmm you tried clearing the cache ? or ran it in incognito? – AutoTester213 Jul 12 '18 at 11:17
  • I didn't try clearing the cache but I did try the incognito, but I got nothing. I've already made adjustment by injecting the javascript with the html file. However I'm still having issues. I tried using but still nothing. I also did the defer (which I'm not sure if i did it correctly) and still nothing. From my adjustments, any idea how to fix my issue? – DayIsGreen Jul 13 '18 at 01:24
0

I've found an answer to my issue. It seems this is not an html issue nor a javascript issue, but rather a socketio issue.

I was using 'socket.broadcast.emit', instead of 'io.sockets.emit'

DayIsGreen
  • 255
  • 1
  • 4
  • 16
0

This a common problem and can be easily rectified by wrapping up your JavaScript code inside

window.setTimeout(function() {

// your js code goes here

}, 500);
Milos
  • 981
  • 3
  • 16
  • 41