Skip to content

Commit df3ea19

Browse files
authored
Allow init_notebook_mode to redefine/reinitialize plotly.js each time it's run (#1452)
* Make sure div exists before calling resize/newPlot functions * Always undef and re-define plotly.js with init_notebook_mode. Checking `!window._Plotly` doesn't save any time and it prevents init_notebook_mode from reinitializing plotly.js in the notebook if things somehow got messed up.
1 parent e53e626 commit df3ea19

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

plotly/offline/offline.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,9 @@ def _build_resize_script(plotdivid, plotly_root='Plotly'):
102102
resize_script = (
103103
'<script type="text/javascript">'
104104
'window.addEventListener("resize", function(){{'
105-
'{plotly_root}.Plots.resize(document.getElementById("{id}"));}});'
105+
'if (document.getElementById("{id}")) {{'
106+
'{plotly_root}.Plots.resize(document.getElementById("{id}"));'
107+
'}};}})'
106108
'</script>'
107109
).format(plotly_root=plotly_root, id=plotdivid)
108110
return resize_script
@@ -289,14 +291,13 @@ def init_notebook_mode(connected=False):
289291
'{win_config}'
290292
'{mathjax_config}'
291293
'<script type=\'text/javascript\'>'
292-
'if(!window._Plotly){{'
294+
'require.undef("plotly");'
293295
'define(\'plotly\', function(require, exports, module) {{'
294296
'{script}'
295297
'}});'
296298
'require([\'plotly\'], function(Plotly) {{'
297299
'window._Plotly = Plotly;'
298300
'}});'
299-
'}}'
300301
'</script>'
301302
'').format(script=get_plotlyjs(),
302303
win_config=_window_plotly_config,
@@ -356,12 +357,14 @@ def _plot_html(figure_or_data, config, validate, default_width,
356357
animate = ''
357358

358359
script = '''
360+
if (document.getElementById("{id}")) {{
359361
Plotly.plot(
360362
'{id}',
361363
{data},
362364
{layout},
363365
{config}
364366
).then(function () {add_frames}){animate}
367+
}}
365368
'''.format(
366369
id=plotdivid,
367370
data=jdata,
@@ -373,7 +376,11 @@ def _plot_html(figure_or_data, config, validate, default_width,
373376
animate=animate
374377
)
375378
else:
376-
script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format(
379+
script = """
380+
if (document.getElementById("{id}")) {{
381+
Plotly.newPlot("{id}", {data}, {layout}, {config});
382+
}}
383+
""".format(
377384
id=plotdivid,
378385
data=jdata,
379386
layout=jlayout,

0 commit comments

Comments
 (0)