Re: Executing script-inserted external scripts in insertion order

On Tue, 12 Oct 2010, Boris Zbarsky wrote:
> On 10/12/10 6:52 AM, Ian Hickson wrote:
> > For those of us who aren't familiar with the products mentioned so far 
> > on this thread, could someone explain why it is interesting to be able 
> > to delay the execution of a batch of scripts until after all those 
> > scripts have been downloaded?
> 
> More precisely, the requirement is that a batch of scripts run in a 
> certain order because some of them depend on others in the batch.
> 
> > It seems to me like it would be simpler to either have all the scripts 
> > download and execute as they become available, with any dependencies 
> > resolved by having the scripts register to be notified when their 
> > dependencies become available
> 
> The use case is to use off-the-shelf scripts that do no such 
> registration and are not even under the control of the page loading them 
> (e.g. Google API scripts, etc) but nevertheless have dependencies on 
> each other.

It seems like this is already possible using <script onload> (optionally 
in conjunction with <link rel=prefetch> to make the UA aware that it can 
start downloading things early):

   function loadScript(scriptSrc, next) {
     var l = document.createElement('link');
     l.rel = 'prefetch';
     l.href = scriptSrc;
     document.getElementsByTagName('head')[0].appendChild(l);
     return function () {
       var s = document.createElement('script');
       s.src = scriptSrc;
       s.onload = next;
       document.body.appendChild(s);
     };
   }

   loadScript('a.js', loadScript('b.js', loadScript('c.js')))();

(There are obviously more straight-forward ways to do it if you prefer 
less functional styles.)

-- 
Ian Hickson               U+1047E                )\._.,--....,'``.    fL
http://ln.hixie.ch/       U+263A                /,   _.. \   _\  ;`._ ,.
Things that are impossible just take longer.   `._.-(,_..'--(,_..'`-.;.'

Received on Tuesday, 12 October 2010 18:59:47 UTC