9

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.

Pratik Goenka
  • 2,321
  • 1
  • 27
  • 24
  • I used the exact same code as you did and it works straight away. Could you tell us which browser, which ipython version, which python version? – Koen May 21 '15 at 11:30
  • @Koen Browser is Chrome, IPython version is 3.0.0 and Python version is 2.7.6 – Pratik Goenka May 21 '15 at 12:08
  • Are you behind a corporate proxy? If you so you may have problems accessing https resources. Try changing the link to http. – RobinL Sep 26 '15 at 15:41
  • Do you have some race condition where the you command the script to load then attempt to print the object before it's downloaded and parsed? – Nick T Oct 09 '15 at 19:28

1 Answers1

11

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:

%%javascript
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.

Nick T
  • 25,754
  • 12
  • 83
  • 121
  • You're a legend, I've been trying to make Javascript work in Jupyter for the last 4 hours. One thing you missed, in the second cell a `%%javascript` over the top would have saved 5 more minutes of agony. Do you know where in the Jupyter documentation they talk about using require? A link to that would make this answer A+++. – Connor Jan 11 '23 at 16:31
  • 1
    @Connor I don't know if they explicitly have docs about using `require`; it's really just using the JS like in any HTML page to avoid race conditions. If there's a basic HTML page that has a ` – Nick T Jan 11 '23 at 19:46