At the recent Facebook/Windows 8 Hackathon hosted at Facebook headquarters, I was helping one group who was bringing a bunch of JavaScript code from a website into their project. They brought all this in with <script> tags at the top of default.html, where default.html contained just a <div data-win-control=”Application.PageControlNavigator” …> as some of the Visual Studio templates provide.

The PageControlNavigator was pointed to the app’s home page in its options, and that page control contained various <canvas> elements that the various JavaScript code attempted to initialize.

Almost everything worked. However, the code that attempted to obtain a canvas element and perform some initialization was failing. More specifically, document.getElementById calls with the canvas IDs were returning null, clearly indicating that those elements did not yet exist in the DOM.

The cause for this was that the code pulled at the top of default.html was all being executed before the PageControlNavigator was able to load the home page contents and attach it to the DOM, thus that page’s elements were not yet available. To correct this, we only needed to move the one bit of code from all those files that started the initialization process into the page control’s ready method, and all was well.

In short, when using page controls, the ready method is where you can be assured that the page’s contents have been loaded and are available for manipulation. The exact timing of how all those elements get into the DOM is different from the direct contents of default.html (and different from what you might know from your browser experience), and so initialization calls need to be in the ready method and not just executed automatically on loading default.html.

Comments are closed