From 89bb120a7cbef665503eccb58bd4f634f0204733 Mon Sep 17 00:00:00 2001 From: Jay Ohms Date: Thu, 4 Nov 2021 23:02:38 -0400 Subject: [PATCH] Update the javascript adapter to support loading Turbo through ESM, which will be deferred. --- turbo/src/main/assets/js/turbo_bridge.js | 36 +++++++++++++++++++----- 1 file changed, 29 insertions(+), 7 deletions(-) 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() + } })()