diff --git a/turbo/src/main/assets/js/turbo_bridge.js b/turbo/src/main/assets/js/turbo_bridge.js index 55af01f4..a787586c 100644 --- a/turbo/src/main/assets/js/turbo_bridge.js +++ b/turbo/src/main/assets/js/turbo_bridge.js @@ -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) @@ -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") } } @@ -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() + } })()