The load event fires after all assets have been loaded, including all images, stylesheets and sub frames. If your code depends on these resources, I’d say using onload
is appropriate. In most cases though, you don’t have to wait that long: just use the DOMContentLoaded
event, it fires as soon as the DOM is ready (see MDN).
Personally, I like to keep the entry function small. It should give others reading your code a top down view of what your program initially does, while hiding the complex details in the functions it calls:
document.addEventListener(`DOMContentLoaded`, main);
function main() {
const state = init();
window.appState = state; // for debugging
state.channels.forEach(name => refresh(state, name));
}
I think it’s a good idea to put function definitions in a wrapper function, because that makes them inaccessible from outside. I’d put them at the bottom of the function to maintain readability. Registering event handlers should be ok, too, however I prefer to have a dedicated function for that.
Declaring variables, like objects, can be problematic, especially when you put all your functions in the entry function as well. Then all your code can access all data. This may seem easier at first, but when you have/want to change how your code works, you suddenly realize that you created a large web of dependencies that is difficult and super-annoying to change.
Compare this:
var mynumber = 3;
console.log(f());
function f() {
return mynumber === -1 || g();
}
function g() {
return mynumber - 10;
}
to this:
start();
function start() {
var mynumber = 3;
console.log(f(mynumber));
}
function f(num) {
return num === -1 || g(num);
}
function g(num) {
return num - 10;
}
If you had to move mynumber
somewhere else, how much code would you have to change?
In the first variant, you’d have to change both functions f
and g
. In the latter, you only have to adjust the parameter you call f
with. While this is a trivial example, this only gets worse as your code becomes more complex. Modular code however, has several advantages, like higher flexibility, reusability and readability as well as easier debugging and unit testing.
tl;dr: Being lazy is not always beneficial 