#!/usr/bin/env python # coding: utf-8 # 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: # # 1. `mything.when_ready` a function that will fire a callback as soon as possible, but not before our resources (whatever they are) are ready. # 2. `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. # # In[11]: get_ipython().run_cell_magic('javascript', '', "\nvar mything = window.mything = {};\n\nmything._ready = false;\nmything._callbacks = [];\n\nmything.when_ready = function (cb) {\n if (mything._ready) {\n // ready, call immediately\n cb();\n } else {\n console.log('not ready, delaying', cb);\n mything._callbacks.push(cb);\n }\n}\n\nmything.get_ready = function () {\n console.log('getting ready')\n mything._ready = true;\n var callbacks = mything._callbacks;\n mything._callbacks = null;\n callbacks.map(function (cb) {\n cb();\n })\n}\n\n// fake a slow thing by calling get_ready after a while\nsetTimeout(function () {\n mything.get_ready();\n}, 2000)\n") # In[12]: get_ipython().run_cell_magic('javascript', '', "\nmything.when_ready(function () {\n console.log('1')\n})\n") # In[13]: get_ipython().run_cell_magic('javascript', '', "\nmything.when_ready(function () {\n console.log('2')\n})\n") # In[ ]: