如何在Ipython笔记本中添加外部javascript文件 [英] How to add external javascript file in Ipython notebook

查看:508
本文介绍了如何在Ipython笔记本中添加外部javascript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样将cdn寄存的d3.js加到我的Ipython笔记本上

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

但是当我加载笔记本第一次得到Javascript错误添加输出,但如果我再次运行单元格它工作正常。我做错了什么?提前感谢。

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.

推荐答案

您可能会导致竞争条件,其中IPython解释器可以快乐地将您的HTML代码段添加到DOM在分割秒,然后还会触发JavaScript命令之前D3js脚本加载/处理。我不是浏览器如何加载/执行JS的专家,但可能有不同的事情,因为你是在页面加载后这样做。

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.

可能overkill,但你可以使用RequireJS(加载反正,因为这是Jupyter用于管理库)。代码段改编自此问题

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

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

require(['d3'], function(d3) {
    console.log("Loaded :)");    
    return {};
});



<


另外,您不需要从IPython.display导入HTML 以使用 %% html 单元格魔术。

这篇关于如何在Ipython笔记本中添加外部javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆