Sometimes you need to load some javascript before displaying output.
RequireJS handles this if your dependencies can be expressed that way (not always possible).
If you can't use rqeuire, you can set up a simple watcher that will detect when your loading has finished and trigger callbacks when loading is done. Any outputs produced after loading is finished will display immediately.
The gist is two methods:
mything.when_ready
a function that will fire a callback as soon as possible, but not before our resources (whatever they are) are ready.mything.get_ready
a function to call when you are done loading, to signal that everything is ready. When called, any delayed callbacks will fire.%%javascript
var mything = window.mything = {};
mything._ready = false;
mything._callbacks = [];
mything.when_ready = function (cb) {
if (mything._ready) {
// ready, call immediately
cb();
} else {
console.log('not ready, delaying', cb);
mything._callbacks.push(cb);
}
}
mything.get_ready = function () {
console.log('getting ready')
mything._ready = true;
var callbacks = mything._callbacks;
mything._callbacks = null;
callbacks.map(function (cb) {
cb();
})
}
// fake a slow thing by calling get_ready after a while
setTimeout(function () {
mything.get_ready();
}, 2000)
%%javascript
mything.when_ready(function () {
console.log('1')
})
%%javascript
mything.when_ready(function () {
console.log('2')
})