JonyEpsilon / gorilla-repl

A rich REPL for Clojure in the notebook style.
http://gorilla-repl.org
MIT License
888 stars 104 forks source link

Conditionally load external JS dependencies #283

Closed heyarne closed 6 years ago

heyarne commented 6 years ago

I'm trying to implement a custom renderer which draws geo data on a leaflet map. To do so, basically two things must happen:

  1. The library (a script and a stylesheet) must be loaded; I figured the easiest way to do that would be to link to a CDN-hosted version
  2. The appropriate elements must be constructed and the rendering code called on them

I My idea was to structure the loading code like this:

if (window.L == null) {
  document.write("<link href=\"...\" />") // + script
}

After leaflet gets loaded the first time it registers a global variable (L), which cause subsequent calls to the above called to be essentially a no-op. This is a well-established code loading pattern in JS. However, when trying to document.write, I loose the whole notebook and I'm left with a page containing only the written string.

What causes this? How do I append these two elements conditionally? Thanks for any help.

heyarne commented 6 years ago

I solved it by using the following pattern:

if (window.L == null) {
  let s = document.getElementsByTagName('script')[0]
  let el = document.createElement('link')
  // set attributes
  s.parentNode.insertBefore(el, s)
}

I'm still unsure why writing to the document causes the expected behavior; my guess is that it has something to do with the knockout.js-integration. I will not investigate any further.

Thanks for the great tool!