Managing Async Dependencies with JavaScript
hackcabin.com
hackcabin.com
I've been using `defer` exclusively ever since I read this: https://calendar.perfplanet.com/2016/prefer-defer-over-async...
The effort that goes into these posts without addressing the basics always boggles my mind.
I naively thought that it would be quicker to have an inline <script> (coming first in the <head>) and have the script request JavaScript resources via XHR (to manage resource dependencies and load failures).
However, the browser decides the priority for resource requests and CPU usage. I found that XHR requests got low priority and wouldn't even get requested until after painting delays.
From a user's perspective, you could create the exact same experience using vanilla XHR (which is exactly what AMD module loading does with `define`).
Believe it or not but currently it's actually the other way around: XHR is defined in terms of fetch:
> XHR is now defined in terms of fetch (see the calls to fetch in XHR's .send()), meaning fetch is lower level than XHR.
Source: https://jakearchibald.com/2015/thats-so-fetch/ and https://xhr.spec.whatwg.org/#the-send%28%29-method
Shortsighted as I am, I struggle to see how fetch-inject guards against SPOF?
Having said that, I can see how this library could be useful for projects with no bundler.
I guess this can be useful, to load extra functionality at run time, in very big single page application.
<script src=... async defer>
for all scripts - could anyone explain?
But how is this different from RequireJS? I think RequireJS uses XHR and I don't think it supports CSS, but aside from that, what's new? I feel like this is just reinventing AMD.
As far as I know, requireJS doesn't do XHR requests and evals. That sounds ugly. I think it dynamically injects a script tag and loads the module. I maybe wrong.
Either way, how's it a blocking one?
So, the only thing that makes fetchInject, differ from requireJS is the non-blocking way. Is my understanding correct?
btw you seem to imply that requirejs blocks - what do you mean by that?
imho this is sufficient:
define('css', function () {
return {
load: function (name, parentRequire, onload, config) {
console.log('loading css ' + name);
const link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = name + '.css';
document.getElementsByTagName('head')[0].appendChild(link);
setTimeout(onload, 0);
}
};
});
usage: require(['lib/js/jquery-ui.min', 'css!lib/css/jquery-ui.min'], function () {
// jquery-ui magic goes here
});