Turbolinks 5: Add external javascript file from other site in a specific page
Asked Answered
A

2

10

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?

Abstract answered 21/2, 2016 at 21:39 Comment(1)
Mordaroso your solution is just fine as per this comment: github.com/turbolinks/turbolinks/issues/…. We could open a PR in the turbolinks gem which will add a helper JavaScript function with the code you posted, so that developers could use it easily, otherwise create a new gem shipping this helper.Isaak
S
0

Check out alphinejs. It was built for that purpose. According to the docs,

Alpine.js offers you the reactive and declarative nature of big frameworks like Vue or React at a much lower cost. You get to keep your DOM, and sprinkle in behavior as you see fit. Think of it like Tailwind for JavaScript.

Splotch answered 25/6, 2020 at 14:31 Comment(0)
T
-1

Nowadays you can try stimulus.

It is born for page specific JavaScript sprinkles.

  • Add a new script tag like <%= javascript_pack_tag 'merchant' %>
  • In the merchant file, you can count on stimulus to handle event for turbolinks and jquery ready.

You can even use webpack and es6.

// hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "name", "output" ]

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}
Thiele answered 24/7, 2018 at 6:35 Comment(2)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewErick
Got it @HarshB. I am new here and still trying to fade in.Thiele

© 2022 - 2024 — McMap. All rights reserved.