Skip to content

Commit 6522c8b

Browse files
authored
Merge pull request #204 from hotwired/esm-compatibility
Update the javascript adapter to support loading Turbo through ESM
2 parents 03de250 + 89bb120 commit 6522c8b

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

turbo/src/main/assets/js/turbo_bridge.js

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
(() => {
2+
const TURBO_LOAD_TIMEOUT = 4000
3+
24
// Bridge between Turbo JS and native code. Built for Turbo 7
35
// with backwards compatibility for Turbolinks 5
46
class TurboNative {
5-
constructor() {
6-
this.registerAdapter()
7-
}
8-
97
registerAdapter() {
108
if (window.Turbo) {
119
Turbo.registerAdapter(this)
@@ -14,8 +12,7 @@
1412
Turbolinks.controller.adapter = this
1513
TurboSession.turboIsReady(true)
1614
} else {
17-
TurboSession.turboIsReady(false)
18-
this.pageLoadFailed()
15+
throw new Error("Failed to register the TurboNative adapter")
1916
}
2017
}
2118

@@ -170,5 +167,30 @@
170167
}
171168

172169
window.turboNative = new TurboNative()
173-
window.turboNative.pageLoaded()
170+
171+
const setup = function() {
172+
window.turboNative.registerAdapter()
173+
window.turboNative.pageLoaded()
174+
175+
document.removeEventListener("turbo:load", setup)
176+
document.removeEventListener("turbolinks:load", setup)
177+
}
178+
179+
const setupOnLoad = () => {
180+
document.addEventListener("turbo:load", setup)
181+
document.addEventListener("turbolinks:load", setup)
182+
183+
setTimeout(() => {
184+
if (!window.Turbo && !window.Turbolinks) {
185+
TurboSession.turboIsReady(false)
186+
window.turboNative.pageLoadFailed()
187+
}
188+
}, TURBO_LOAD_TIMEOUT)
189+
}
190+
191+
if (window.Turbo || window.Turbolinks) {
192+
setup()
193+
} else {
194+
setupOnLoad()
195+
}
174196
})()

0 commit comments

Comments
 (0)