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.
-
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– Koen2015年05月21日 11:30:59 +00:00Commented May 21, 2015 at 11:30
-
@Koen Browser is Chrome, IPython version is 3.0.0 and Python version is 2.7.6Pratik Goenka– Pratik Goenka2015年05月21日 12:08:57 +00:00Commented May 21, 2015 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– RobinL2015年09月26日 15:41:15 +00:00Commented Sep 26, 2015 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– Nick T2015年10月09日 19:28:53 +00:00Commented Oct 9, 2015 at 19:28
1 Answer 1
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 HTMLto use the%%htmlcell magic.
2 Comments
%%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+++.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 <script src="https://example.com/cdn/my.js"> then you try to use it in the next line with some inline JS, it'll fail because the browser immediately tries to run it, while it's just barely started to even request the remote script, let alone get it or execute it.