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

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

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. Required fields are marked *