W3C home > Mailing lists > Public > whatwg@whatwg.org > February 2011

[whatwg] Proposal for separating script downloads and execution

From: Glenn Maynard <glenn@zewt.org>
Date: Sat, 12 Feb 2011 23:22:54 -0500
Message-ID: <AANLkTi=8tGKveQSZido3X3EYkC9=M1wO0X7ixA-4+-yW@mail.gmail.com>
On Fri, Feb 11, 2011 at 7:31 PM, Glenn Maynard <glenn at zewt.org> wrote:

> I think the example code can be simplified a lot to demonstrate the API
> more clearly.  I've attached a simplified version.  It also explicitly
> catches exceptions from execute() and calls errorCallback, and demonstrates
> feature checking (in a simpler way).
>

The list archives don't seem to archive attachments.  Here's the above
attachment inline, so it's not missing for anyone reading this thread in the
archives later (at least one person's mail server also bounced it).

One other note: If the script called via execute() raises an exception, it
makes more sense for that exception to be raised by execute(), as if the
loaded script is simply a function being called (which it essentially is).
The current proposal's "equivalent of the following..." comparison implies
that exceptions from the called script go right to the browser.  I'd suggest
removing the "equivalent" code and being explicit about what should happen.


function loadScripts(urls, successCallback, errorCallback)
{
        var scripts = [];
        var loaded = 0;

        if(typeof HTMLScriptElement.prototype.execute != "function")
                throw "Preloading not supported";

        for(var i = 0; i < urls.length; ++i)
        {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.preload = true;
                script.onpreload = function(event)
                {
                        ++loaded;
                        if(loaded < urls.length)
                                return;

                        try {
                                for (var i=0; i<scripts.length; i++)
                                        scripts[i].execute();
                        } catch(e) {
                                errorCallback();
                                throw e;
                        }

                        successCallback();
                }
                script.onerror = errorCallback;
                script.src = urls[i];

                scripts.push(script);
                document.head.appendChild(script);
       }
}

// usage
loadScripts(["foo.js", "bar.js"],
        function()
        {
                foo.init();
        },
        function()
        {
                alert("On no!");
        }
);


-- 
Glenn Maynard
Received on Saturday, 12 February 2011 20:22:54 UTC

This archive was generated by hypermail 2.4.0 : Wednesday, 22 January 2020 16:59:30 UTC