When you want to use a asynchronous loading technique (like requireJS for instance) in a Windows HTML application you can have trouble catching the activation event due to the fact that WinJS.Application.start() must be called synchronously at the start of the process in order to register with the system's activation handler at the right time.
Here is a code snippet which describes a way to work around that by using an artifical event to stall the WinJS.Application event queue until your activation handler is registered and ready to run.
(function () {
"use strict";
// Alias the application object
var app = WinJS.Application;
// When using require and you need to wait to register your activated event handler
// until the dependent modules have loaded you still need to call app.start()
// synchronously at startup, in order to facilitate this we take advantage of the
// ordering characteristics and extensibility of the WinJS.Application event
// queue and introduce a (arbitrary) "wait" event that blocks the queue until
// your activation handler is registered.
//
// First we create a promise which will be used to block the queue and smuggle
// out the complete handler so we can call it later.
var activateRegistered;
var activateRegisteredPromise = new WinJS.Promise(function (c) {
activateRegistered = c;
});
//
// Then we register a "wait" event handler which simply blocks on the promise.
app.addEventListener("wait", function (args) {
args.setPromise(activateRegisteredPromise);
});
//
// Then we queue a "wait" event ahead of activation (before app.start()).
app.queueEvent({ type: "wait" });
//
// Calling app.start makes the application model register for the system's activated
// event and dispatches the "wait" event we have queued.
app.start();
// Use require to load modules asynchonrously
require(["log"], function (log) {
var logger = log.logger("app");
// When you have modules loaded register your activated event handler
app.onactivated = function (args) {
// Do whatever you want in your activation handler...
};
// Then after your activated handler has been registered complete the
// outstanding promise which will unblock the queue and allow other events
// to pump including the queued up activation event.
activateRegistered();
});
})();
Yeah, I was thinking about the bytecode optimizations too. Do they work with dynamically loaded script?