Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add external javascript file in Ipython notebook

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

Ipython Notebook

But when I load the notebook first time I get "Javascript error adding output", but if I run cell again it works properly. Am I doing something wrong? Thanks in advance.

like image 222
Pratik Goenka Avatar asked May 21 '15 07:05

Pratik Goenka


1 Answers

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.

like image 131
Nick T Avatar answered Oct 02 '22 16:10

Nick T