I'm trying to lazy load livewire and alpine libs after page completely loads.
So, I have some progress in here, but, one issue, that alpine do no see livewire's methods, like emitTo
Here is my loader:
<script defer {{ $attributes }}>
function loadLivewire() {
let script = document.createElement('script');
script.src = '{{ $fullAssetPath }}';
script.setAttribute('data-turbo-eval', 'false');
script.setAttribute('data-turbolinks-eval', 'false');
document.body.append(script);
setTimeout(() => {
window.Livewire = new Livewire();
window.Livewire.devTools({{ var_export($shouldDebug) }});
window.livewire_app_url = '{{ $appUrl }}';
window.livewire_token = '{{ $jsLivewireToken }}';
window.Livewire.start();
window.deferLoadingAlpine = function (callback) {
window.addEventListener('livewire:load', function () {
callback();
});
};
window.addEventListener("alpine:initializing", function () {
window.Livewire.start();
});
loadAlpine();
}, 50);
}
function loadAlpine() {
document.addEventListener('alpine:init', () => {
Alpine.store('app', {
sidebarOpen: false,
selectedRepresentative: null,
formOpen: null,
modalOpen: null,
recaptchaSitekey: null,
addressesModalOpen: null,
recallOpen: null
});
});
let script = document.createElement('script');
script.src = 'https://unpkg.com/alpinejs@3.4.1/dist/cdn.min.js';
document.body.append(script);
}
window.addEventListener('load', () => {
setTimeout(() => {
loadLivewire();
}, {{ $timeout }});
});
</script>
All fine unless i click on some button that uses livewire logic, and then I got this:
VM128705:3 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'emitTo')
at eval (eval at generateFunctionFromString (cdn.js:380), <anonymous>:3:48)
at cdn.js:391
at tryCatch (cdn.js:415)
at cdn.js:2595
at handler3 (cdn.js:2054)
at cdn.js:2075
at cdn.js:2056
at cdn.js:2097
at HTMLButtonElement.<anonymous> (cdn.js:2056)