Archive for the ‘winmo’ tag

JS Lazyload for Windows Mobile 6.5 widgets

without comments

It took me the better part of  the afternoon, but I tamed it.

I am creating a widget that has to run on different devices. I implemented a lazy loader to loadmost of the javascript files and it worked on all my targets, except Windows Mobile 6.5. I wanted to be notified when all the files were loaded to proceed to my main app init code, but it was not working on the WM6.5 widget context. On the browser it worked, but when packaged as a widget it didn’t.

I thought I had hit a brick wall and had to resort to something (more) hackish, but in the end the perserverance  paid off, with a little luck.

First, for some reason, the attachEvent method does not exist on a script element when running as a widget, although it exists on Mobile IE, which was why it worked.

Poking at a newly created script object, I noticed a onreadystatechange property. Experimenting with it on a live widget I managed to make it call my callback function once, but when I tried to put it to use on my code it didn’t.

After much debugging, in which Bluetooth File Transfer.app didn’t help (on 10.6.2 it crashes 80% of the time when transferring a file to a WM device), I figured it out.

I was creating the new script object, setting all the properties and then adding it to the DOM. This seemed to be a sensible solution, but it didn’t work in this case. Then I tried to add the script element to the DOM, immediately  after its creation. Bingo! It worked. I only set the “src” property in the end, to prevent loading the script before I have the chance to set the onreadystatechange callback and everything else. I don’t know if this is really needed, but after wasting lots of time on this today I’ll wait until tomorrow to find out. :)

I don’t know if this code is still working on the other platforms, but I don’t see any reason not to. Then again, I better check. :)

Here is the relevant code. I’m posting it here in case some poor soul stumps on the same problem. “cb” is the callback function.

var script = document.createElement("script");
document.getElementsByTagName("head")[0].appendChild(script);
if (script.addEventListener) {
    script.addEventListener("load", cb, false);
} else if (script.attachEvent) {
    script.attachEvent("onreadystatechange", function() {
        if (script.readyState == "loaded") {
            cb();
        }
    });
}  else {
    script.onreadystatechange = function () {
        cb();
    };
}
script.type = "text/javascript";
script.src = name;

Mental note, I need some wordpress plugin for posting code.

Written by Pedro Cardoso

March 2nd, 2010 at 11:01 pm

Posted in Uncategorized

Tagged with , , , ,