How to add external javascript file in Ipython notebook

前端 未结 1 1801
半阙折子戏
半阙折子戏 2020-12-31 17:34

I am trying to add cdn hosted d3.js to my Ipython notebook like this

\"Ipython

But when I l

相关标签:
1条回答
  • 2020-12-31 18:09

    You're likely causing a race condition where the IPython interpreter can happily add your HTML snippet to the DOM in a split second, then also fires off the JavaScript command before the D3js script is loaded/processed. I'm not an expert on how the browser loads/executes JS, but there might be something different going on because you're doing it after the page has loaded.

    Probably overkill, but you could use RequireJS (loaded anyways, as that's what Jupyter uses to manage libraries). Snippet adapted from this question:

    First Cell:

    %%javascript
    requirejs.config({
        paths: { 
            'd3': ['//cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3'], 
        },                                         // strip .js ^, require adds it back
    });
    

    Any cell that needs d3js, wrap the call (e.g. your console.log(d3);) in the following:

    require(['d3'], function(d3) {
        console.log(d3);  // or whatever
        return {};
    });
    

    A hackier solution might be to just add a time.sleep(1) between those two cells.

    As an aside, you don't need to from IPython.display import HTML to use the %%html cell magic.

    0 讨论(0)
提交回复
热议问题