@@ -52,30 +52,34 @@ var toggleTheme = () => {
5252 ========================================================================== */
5353
5454// Read the Plotly data from the code block, hide it, and render the chart as new node. This allows for the
55- // JSON data to be retrieve when the theme is switched.
55+ // JSON data to be retrieve when the theme is switched. The listener should only be added if the data is
56+ // actually present on the page.
5657import { plotlyDarkLayout , plotlyLightLayout } from './theme.js' ;
57- document . addEventListener ( "readystatechange" , ( ) => {
58- if ( document . readyState === "complete" ) {
59- document . querySelectorAll ( "pre>code.language-plotly" ) . forEach ( ( elem ) => {
60- // Parse the Plotly JSON data and hide it
61- var jsonData = JSON . parse ( elem . textContent ) ;
62- elem . parentElement . classList . add ( "hidden" ) ;
63-
64- // Add the Plotly node
65- let chartElement = document . createElement ( "div" ) ;
66- elem . parentElement . after ( chartElement ) ;
67-
68- // Set the theme for the plot and render it
69- const theme = ( determineComputedTheme ( ) === "dark" ) ? plotlyDarkLayout : plotlyLightLayout ;
70- if ( jsonData . layout ) {
71- jsonData . layout . template = ( jsonData . layout . template ) ? { ...theme , ...jsonData . layout . template } : theme ;
72- } else {
73- jsonData . layout = { template : theme } ;
74- }
75- Plotly . react ( chartElement , jsonData . data , jsonData . layout ) ;
76- } ) ;
77- }
78- } ) ;
58+ let plotlyElements = document . querySelectorAll ( "pre>code.language-plotly" ) ;
59+ if ( plotlyElements . length > 0 ) {
60+ document . addEventListener ( "readystatechange" , ( ) => {
61+ if ( document . readyState === "complete" ) {
62+ plotlyElements . forEach ( ( elem ) => {
63+ // Parse the Plotly JSON data and hide it
64+ var jsonData = JSON . parse ( elem . textContent ) ;
65+ elem . parentElement . classList . add ( "hidden" ) ;
66+
67+ // Add the Plotly node
68+ let chartElement = document . createElement ( "div" ) ;
69+ elem . parentElement . after ( chartElement ) ;
70+
71+ // Set the theme for the plot and render it
72+ const theme = ( determineComputedTheme ( ) === "dark" ) ? plotlyDarkLayout : plotlyLightLayout ;
73+ if ( jsonData . layout ) {
74+ jsonData . layout . template = ( jsonData . layout . template ) ? { ...theme , ...jsonData . layout . template } : theme ;
75+ } else {
76+ jsonData . layout = { template : theme } ;
77+ }
78+ Plotly . react ( chartElement , jsonData . data , jsonData . layout ) ;
79+ } ) ;
80+ }
81+ } ) ;
82+ }
7983
8084/* ==========================================================================
8185 Actions that should occur when the page has been fully loaded
0 commit comments