Skip to content

Commit

Permalink
Update the javascript adapter to support loading Turbo through ESM, w…
Browse files Browse the repository at this point in the history
…hich will be deferred.
  • Loading branch information
jayohms committed Nov 5, 2021
1 parent 03de250 commit 89bb120
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions turbo/src/main/assets/js/turbo_bridge.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
(() => {
const TURBO_LOAD_TIMEOUT = 4000

// Bridge between Turbo JS and native code. Built for Turbo 7
// with backwards compatibility for Turbolinks 5
class TurboNative {
constructor() {
this.registerAdapter()
}

registerAdapter() {
if (window.Turbo) {
Turbo.registerAdapter(this)
Expand All @@ -14,8 +12,7 @@
Turbolinks.controller.adapter = this
TurboSession.turboIsReady(true)
} else {
TurboSession.turboIsReady(false)
this.pageLoadFailed()
throw new Error("Failed to register the TurboNative adapter")
}
}

Expand Down Expand Up @@ -170,5 +167,30 @@
}

window.turboNative = new TurboNative()
window.turboNative.pageLoaded()

const setup = function() {
window.turboNative.registerAdapter()
window.turboNative.pageLoaded()

document.removeEventListener("turbo:load", setup)
document.removeEventListener("turbolinks:load", setup)
}

const setupOnLoad = () => {
document.addEventListener("turbo:load", setup)
document.addEventListener("turbolinks:load", setup)

setTimeout(() => {
if (!window.Turbo && !window.Turbolinks) {
TurboSession.turboIsReady(false)
window.turboNative.pageLoadFailed()
}
}, TURBO_LOAD_TIMEOUT)
}

if (window.Turbo || window.Turbolinks) {
setup()
} else {
setupOnLoad()
}
})()

0 comments on commit 89bb120

Please sign in to comment.