Shun window.onload in HTML5 games

A lot of javascript developers have been using window.onload casually in their code but this is something which we should completely avoid since window.onload is only called once and if there are multiple window.onload events, then only the last onload event gets called.

In our Phaser games we normally initialize the game as following

var mygame;
window.onload = function() {
    mygame = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, "mygame");

    mygame.state.add("Boot", Boot);
    mygame.state.add("Loading", Loading);
    mygame.state.add("MyGame", MyGame);
    mygame.state.start("Boot");
};

window.onload is called after the main HTML, all CSS files, images and other resources have been loaded and rendered. We don’t want to stall loading of the game and its resources until everything else on the page has been loaded and rendered so as soon as initial HTML document has been loaded and parsed, we can start loading our game without waiting for page stylesheets, images, etc to finish loading. An alternate approach for this using vanilla javascript would be

var mygame
var loadGame = function () {
    mygame = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, "mygame");

    mygame.state.add("Boot", Boot);
    mygame.state.add("Loading", Loading);
    mygame.state.add("MyGame", MyGame);
    mygame.state.start("Boot");
};

if (document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll)) {
    loadGame();
} else {
    document.addEventListener("DOMContentLoaded", loadGame);
}

This starts loading the game as soon as HTML DOM is parsed and ready and no fear of having to change the code in future if we decided to use some other code or external librray which is depenedent on window.onload.

Read more about DOMContentLoaded and document.readyState.


Leave A Comment

Your email address will not be published.