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.


One Trackback

  1. By Author news: Announcing Kraig Brockschmidt’s blog | MSDN Blogs on January 12, 2013 at 10:59 pm

    [...] useful insights (like Simultaneously debugging script and managed/native code in Windows 8 and A Page Navigation Gotcha), and, well, you get the idea. I think it’ll be worth subscribing [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>