I am making a NodeJS app with Express and Socket.io. I am trying to send some data in the form of an object from the server to the client, and I want this to happen when the page has been loaded. Then, some HTML can be changed with the object that's been received. I'm pretty sure that this is possible with Socket.io. However, when using window.onload = function() {...}
, nothing happens. window.onload
isn't even called.
When I try this without using NodeJS (just using the HTML page), it works fine. window.onload
is called and all goes well. So why isn't this working within NodeJS? I know that it waits for all images, etc. to load and was having a problem with that, but that's been mostly resolved now. The image is loading fine. (I still can't load it with background-image
though, does this make a difference?)
Also, am I going the correct way about sending data from server to client? I'd much rather use Socket.io than learn something new like Angular or React.
Here's my code:
main.js (client)
window.onload = function() {
console.log('window loaded'); // this shows when not in NodeJS app
alert('window ready'); // neither does this
socket.emit('pageReady'); // so this doesn't run
}
socket.on('pageInfo', function(response) {
console.log('page info received'); //this doesn't run either
document.getElementById("schoolName").innerHTML = response.school_name;
});
app.js (server)
io.on('pageReady', function() {
io.emit('pageInfo', response); // response is defined earlier
console.log('page ready recieved'); // this doesn't show
});