Qoopido.demand is a modular, flexible and 100% async JavaScript module loader with a promise like interface that utilizes localStorage as a caching layer. It comes in a rather tiny package of ~7kB minified and gzipped.
Qoopido.demand originated from my daily use of require.js for the initial development of my Qoopido.nucleus library which is strictly atomic by nature, unbundled.
genie includedQoopido.demand is developed for Chrome, Firefox, Safari, Edge, Opera and IE11+.
Active Support for IE9 and IE10 has been removed in Qoopido.demand 6.0.0 due to upcoming refactorings/cleanups and the lack of market share of these browsers today.
Support for IE8 has been actively removed in Qoopido.demand 4.0.0 due to the lack of justifiable polyfills for parts of some underlying pattern.
I do test on MacOS Sierra where Qoopido.demand is fully working on Chrome, Firefox, Safari and Opera. IE9, 10, 11 as well as Edge are testet on the official Microsoft VMs via VirtualBox.
Due to modules getting loaded via XHR a remote server has to have CORS enabled. Be assured that most of the usual CDNs have CORS enabled by default.
None!
Qoopido.demand is available on GitHub as well as jsdelivr, npm and bower at the moment.
Use the following minified code snippet in a standalone script tag before the closing body tag to include demand:
(function(url, main, settings) {
!function(e,n,t,r,s){r=n.getElementsByTagName(t)[0],s=n.createElement(t),e.demand={url:url,main:main,settings:settings},s.async=1,s.src=url,r.parentNode.insertBefore(s,r)}(window,document,"script");
}('../dist/demand.js', './app/main', { base: './', version: '1.0.0', cache: true }));
The snippet is very similar to Google Analytics. The outer function allows you to specify an URL from which to load demand itself as well as a path to the main module and configuration object for demand. The script tag that actually loads Qoopido.demand will be injected with its async attribute set.
As an alternative to the above snippet Qoopido.demand can now also be loaded with an alternative snippet that uses an iframe. The async method above, while not blocking rendering, seems to delay the onload event at least on some browsers. The iframe method solves this minor annoyance.
(function(url, main, settings) {
!function(e,t,n,o,i,d,a){e.demand={url:url,main:main,settings:settings},o=t.getElementsByTagName(n)[0],i=t.createElement("iframe"),i.src="https://github.com/dlueth/qoopido.demand/raw/8.0.2/javascript:void(0)",i.name="demand-loader",i.title="",i.role="presentation",(i.frameElement||i).style.cssText="display:none;width:0;height:0;border:0;",o.parentNode.insertBefore(i,o);try{i=i.contentWindow.document}catch(e){d=t.domain,i.src='javascript:var d=document.open();d.domain="'+d+'";void(0);',i=i.contentWindow.document}i.open()._=function(){d&&(this.domain=d),a=this.createElement(n),a.src=url,this.body.appendChild(a)},i.write('<body onload="document._();" />'),i.close()}(this,document,"script");
}('../dist/demand.js', './app/main', { base: './', version: '1.0.0', cache: true }));
Remember to adjust parameters according to the async method.
The last parameter of the above code snippet is a configuration object. It just contains base and version as these are the properties you will most likely set. There are some more, less frequently used, options that can be either specified here or as part of a demand.configure call in your main module (being described in the next section):
{
// enables or disables caching in general (when true/false)
// optional, defaults to "true"
cache: true,
// fine grained cache control (when object)
// any path or part of a path can be set to true to
// activate caching or false to disable it.
// The longest matching path wins over others.
cache: {
'/demand/': true,
'/app/': true,
'/app/nocache': false
},
// cache will be validated against version
// optional, defaults to "undefined"
version: '1.0.0',
// cache will be validated against lifetime, if > 0
// optional, defaults to "0"
// unit: seconds
lifetime: 60,
// sets the timeout for XHR requests
// optional, defaults to "8" (limited to "2" up to "20")
// unit: seconds
timeout: 8,
// base path from where your relative
// dependencies get loaded
// optional, defaults to "/"
base: '[path/url to your scripts]',
// optional
pattern: {
'/nucleus': ['[path/url to Qoopido.nucleus]', '[fallback path/url to Qoopido.nucleus]'],
'/app': '[path/url to your modules]',
// just an example, loading jQuery + bundle
// will not work due to the nature of jQuery
'/jquery': '//cdn.jsdelivr.net/jquery/2.1.4/jquery.min',
'/jquery+ui': '//cdn.jsdelivr.net/g/jquery@2.1.4,jquery.ui@1.11.4'
},
// per module configuration (if applicable)
modules: {
// configure the legacy handler
'/demand/handler/legacy': {
'/jquery': {
probe: function() { return global.jQuery; }
},
'/jquery/ui': {
probe: function() { return global.jQuery.ui; },
dependencies: [ 'legacy!/jquery' ]
},
'/velocity': {
probe: function() { return global.Velocity || (global.jQuery && global.jQuery.fn.velocity); }
},
'/leaflet': {
probe: function() { return global.L; }
}
}
// configure the bundle handler
'/demand/handler/bundle': {
// declare which modules are included in the bundle
// order is important
'/jquery+ui': [ '/jquery', '/jquery/ui' ]
},
// configure genie plugin
'/demand/plugin/genie': {
// handle creation of auto-bundle URL for Qoopido.nucleus from jsdelivr
'/nucleus/': function(dependencies) {
var fragments = [],
i = 0, dependency;
for(; (dependency = dependencies[i]); i++) {
fragments.push(dependency.id.replace(/^\/nucleus\//, '') + '.js');
}
return '//cdn.jsdelivr.net/g/qoopido.nucleus@2.0.1(' + fragments.join('+') + ')';
},
// handle creation of auto-bundle URL for your modules from your server
'/app/': function(dependencies) {
var fragments = [],
i = 0, dependency;
for(; (dependency = dependencies[i]); i++) {
fragments.push(dependency.id.replace(/^\/js\//, '') + '.js');
}
return '/genie/?module[]=' + fragments.join('&module[]=');
}
}
}
The demanded main module from the above script might look like the following example:
(function(global) {
'use strict';
function definition(demand, provide) {
demand
.configure({
// any option from the previous section
// most likely something like:
pattern: {
},
modules: {
}
});
return true; // just return true if there really is nothing to return
}
provide([ 'demand', 'provide' ], definition);
}(this));
Qoopido.demand consists of two components demand and provide just like require.js require and define.
Once demand is loaded anything that is either explicitly requested via demand or as a dependency of a provide call will be loaded via XHR as well as modified and injected into the DOM with the help of a handler. The result will be cached in localStorage (if caching is enabled and localStorage is available) that will get validated against an optional version and lifetime set via demand.configure or the modules path declaration (more on that later).
As main itself is also loaded as a module it will get cached in localStorage as well.
If caching is enabled, localStorage available and its quota not exceeded chances are good you will never have to manually deal with the cache.
By default demand will invalidate a modules cache under the following conditions:
version changedlifetime is exceededDemand will, in addition, do its best to keep leftover garbage to a minimum. It does so by starting an automatic garbage collection for expired caches on load. In addition it will also clear a specific cache if it gets requested and is found to be invalid for any reason.
When localStorage quota is exceeded while trying to cache yet another module Qoopido.demand will load a special module /demand/cache/dispose and will try to free the required space by clearing existing caches in order of last access time, from oldest to newest.
Beside the automatic cache invalidation demand still offers manual control by registering a demand.cache object to the global demand function. This object offers the following methods to control the cache:
// only clear a single module's cache
demand.cache.clear('[module path]');
// clear all expired caches
demand.cache.clear.expired();
// completely clear the cache
demand.cache.clear.all();
Sidenote
Demand does use a prefix for its localStorage keys to prevent conflicts with other scripts. Each cache will consist of two keys, one to store the
stateinformation and one for the actualvalue(source) of the module. By separating the two only a very small string will have to get parsed to retrieve the state.
After your project is set up accordingly you can load further modules like in the following example:
demand('./app/test', '/nucleus/component/iterator')
.then(
function(appTest, nucleusComponentIterator) {
console.log('=> success', appTest, nucleusComponentIterator);
new nucleusComponentIterator();
},
function() {
console.log('=> error', arguments);
}
);
Relative module paths will be resolved relative to the base path or the path of an eventual parent module (see section Path resolution). The resulting path will afterwards get matched against patterns defined via demand.configure which will finally lead to an absolute URL to fetch the module from.
Sidenote
The rejection function will be passed all rejected dependencies as arguments, not only the first one rejected.
If no handler is specified it will default to the module handler. If you would like to load e.g. CSS simply prefix your path with css!.
Beside its global configuration Qoopido.demand also allows per module or subpath configuration for general cacheability, versioning and lifetime. All per module settings are optional parts of its path declaration.
You already learnt that a prefix of css! tells Qoopido.demand to use the CSS handler for the module. All other possible options are also part of the path declaration, for example
demand('css@2.0.4#2000!AnyCssModule').then(
function() {}
);
will tell Qoopido.demand to load your AnyCssModule via the CSS handler and cache it at version 2.0.4 for 2000 seconds if cache is enabled either globally or for this specific module via demand.configure. You may, in rare cases, want to force a module to either be cached or not overriding any global configuration which can be done by:
demand('-css!AnyCssModule').then(
function() {}
);
Prefixing the module's path with a - will completely disable any caching for this specific demand call whereas prefixing it with a + will force it to be cached disregarding any global cache settings.
As any parameter that is part of the path declaration is optional you gain total control over when and how Qoopido.demand caches your modules!
Qoopido.demand's original idea was (and still is) to not need a server-side built-process to pre-compile static bundles but to directly load any module required on demand. This decision really embraces new technologies like HTTP/2 that do not establish a new connection for each single request but instead are able to handle all requests with a single connection.
While this is absolutely great HTTP/2 is not 100% supported by servers and clients yet and even if it is, requesting many assets may still slow down your perceived loading experience.
To handle this Qoopido.demand has a built-in plugin called genie which can be configured to create auto-bundle requests for all direct dependencies of a module. To give you a more detailed example think about a module depending on /nucleus/dom/element, /nucleus/dom/collection and /nucleus/component/sense.
If ```g
$ claude mcp add qoopido.demand \
-- python -m otcore.mcp_server <graph>