[whatwg] Promise-vending loaded() & ready() methods on various elements

Kyle Simpson getify at gmail.com
Fri Mar 14 13:10:09 PDT 2014


> This, along with Ilya's proposed <link rel="preload"> (
> https://docs.google.com/a/google.com/document/d/1HeTVglnZHD_mGSaID1gUZPqLAa1lXWObV-Zkx6q_HF4/edit#heading=h.x6lyw2ttub69),
> and JavaScript modules (
> https://github.com/dherman/web-modules/blob/master/module-tag/explainer.md)
> gives us everything we need for sane & versitile dependency loading.


Is <link rel=preload> going to fire this "loaded" event after it finishes pre-loading but BEFORE it executes (or, rather, BEFORE because it doesn't execute them at all)? Because for <script>, the "load" event fires only after it has loaded AND executed, which is of course "too late" for many of the more advanced use-cases below.

If you want to dynamically *preload* scripts (that is, you don't have <link rel=preload> tags in your initial page markup) later on in the lifetime of the page, is the story basically like this?



function preloadScript(src) {
   var l = document.createElement("link");
   l.rel = "preload";
   l.href = src;
   document.head.appendChild(l);
   return l.loaded();
}

function execScript(l) {
   var s = document.createElement("script");
   s.src = l.href;
   document.head.appendChild(s);
   return s.loaded();
}

Promise.all(
   preloadScript("a.js"),
   preloadScript("b.js"),
   preloadScript("c.js")
)
.then(function(links){
   return Promise.all.apply(null,links.map(execScript));
})
.then(function(){
   alert("All scripts loaded and executed");
});
   


So, if that's how we think this would work, we need to understand how the `execScript(..)` logic is going to be treated. Is creating a <script> element dynamically and inserting it going to make sure that it either:

  a. executes sync
  b. executes async, but "a.js" will *definitely* execute before "b.js", which will *definitely* execute before "c.js".

In other words, is there any possibility that it won't execute in order "a" -> "b" -> "c" in the above code? If so, do/don't we have to be more complex, like?



Promise.all(
   preloadScript("a.js"),
   preloadScript("b.js"),
   preloadScript("c.js")
)
.then(function(links){
   var chain;
   links = links.forEach(function(link){
      if (!chain) chain = execScript(link);
      else chain = chain.then(function(){ return execScript(link); });
   });
   return chain;
})
.then(function(){
   alert("All scripts loaded and executed");
});




--Kyle







More information about the whatwg mailing list