I am using turbolinks 5 beta 1 and for some specific pages I want to load an external javascript file.
In my example I have a contacts page where I want to display a map by loading google maps api. It should not be loaded when accessing the root page but then later be included after clicking the link to the contacts page.
Yielding a javascript script tag worked in Turbolinks 2. But seems not to work anymore.
There would the possibility to check if the javascript is already loaded and otherwise load it asynchronously if needed.
Something like this:
loadScript = (src, callback) ->
script = document.createElement("script")
script.type = "text/javascript"
script.onload = callback if callback
document.getElementsByTagName("head")[0].appendChild(script)
script.src = src
initialize = ->
# init map here
load = ->
if $('#gmap').size > 0
if typeof(google) == 'function'
initialize()
else
loadScript 'https://maps.googleapis.com/maps/api/js?&callback=initialize'
$(document).on 'turbolinks:load', -> load()
Is this the only way to handle this problem or is there an easier way?