const loadImage = (url) => new Promise((resolve, reject) => { const img = new Image(); img.addEventListener('load', () => resolve(img)); img.addEventListener('error', (err) => reject(err)); img.src = url; }); document.addEventListener('alpine:init', () => { Alpine.data('logo', () => ({ logoPhase: 0, phases: { 1: 'images/lf-anim-simple.gif', 2: 'images/lf-anim.gif', }, sidebar: true, init() { console.log("logo init"); this.preloadPhase(1); }, togglePhase() { var phase = this.sidebar ? 1 : 2; if (phase in this.phases) { console.log("reloading logo phase", phase); this.$el.style.backgroundImage = 'url(' + this.phases[phase] + ')'; } }, preloadPhase(phase) { console.log("loading logo phase", phase); console.log("phase exists", phase in this.phases); if (phase in this.phases) { this.logoPhase = phase; loadImage(this.phases[phase]) .then(img => { console.log("swapping src") this.$el.style.backgroundImage = 'url(' + img.src + ')'; this.preloadPhase(this.logoPhase+1); }) .catch(err => console.error(err)); } else { console.log("logo loading complete"); } }, })) })