diff --git a/layouts/partials/footer.html b/layouts/partials/footer.html index 6561ad6..9283db6 100644 --- a/layouts/partials/footer.html +++ b/layouts/partials/footer.html @@ -23,30 +23,54 @@ const searchElement = document.getElementById('search'); const toggleButton = document.getElementById('toggle-search'); - const ensureSearch = () => { - if (searchState.initialized || !searchElement) { - return; + const waitForSearchInput = () => new Promise((resolve) => { + const findInput = () => { + const input = searchElement.querySelector('input'); + if (input) { + resolve(input); + return; + } + + window.requestAnimationFrame(findInput); + }; + + findInput(); + }); + + const ensureSearch = async () => { + if (!searchElement) { + return null; + } + + if (searchState.initialized) { + return searchElement.querySelector('input'); + } + + if (searchState.initializing) { + return waitForSearchInput(); } if (typeof window.PagefindUI !== 'function') { searchElement.innerHTML = '

Search is currently unavailable.

'; searchState.initialized = true; - return; + return null; } + searchState.initializing = true; searchState.instance = new PagefindUI({ element: "#search", showSubResults: false }); searchState.initialized = true; + searchState.initializing = false; + return waitForSearchInput(); }; if (toggleButton && searchElement) { - toggleButton.addEventListener('click', () => { + toggleButton.addEventListener('click', async () => { const isHidden = searchElement.hasAttribute('hidden'); if (isHidden) { - ensureSearch(); searchElement.removeAttribute('hidden'); toggleButton.setAttribute('aria-expanded', 'true'); - const input = searchElement.querySelector('input'); + const input = await ensureSearch(); if (input) { input.focus(); } diff --git a/layouts/partials/head.html b/layouts/partials/head.html index cb6e772..154dd8f 100644 --- a/layouts/partials/head.html +++ b/layouts/partials/head.html @@ -30,17 +30,18 @@ {{ else -}} | DE {{ end }} - | - +