From ba3494e4490e0f1bc6d5b6a800c9a36edd9a47bc Mon Sep 17 00:00:00 2001 From: Sebastian Serth Date: Thu, 15 Aug 2024 18:38:32 +0200 Subject: [PATCH] Ensure select2 is initialized regardless of page load events Previously, select2 was only loaded successfully, if first the page was loaded (turbolinks:load) and then all select2 locales (select2:locales:loaded). However, if the order was different, select2 wouldn't be initialized. Fixes #1476 --- app/javascript/application.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/app/javascript/application.js b/app/javascript/application.js index 912021178..09dca8e5b 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -50,8 +50,15 @@ import locales from "../../tmp/locales.json"; Promise.all( Object.keys(locales).map(locale => import(`select2/dist/js/i18n/${locale}`)) -).then(() => - document.dispatchEvent(new Event("select2:locales:loaded")) +).then(() => { + // Since there is a race condition between the locales and turbolinks, + // we don't know whether the locales are loaded before or after turbolinks. + // Therefore, we trigger the event in both cases. + $(document).on('turbolinks:load', () => + $(document).trigger('select2:locales:loaded') + ); + $(document).trigger('select2:locales:loaded') + } ); // Fetch user locale from html#lang.