How to subscribe to ready event when lazy-loading

I set loadingStrategy to ‘on-user-interaction’ (although I think it’s sub-optimal, loading even on mouse-move, but that’s off-topic) - and I’d like to subscribe to ready event.

But the Snipcart.subscribe method does not exist when snipcart.js is not loaded yet.

In the best case I would even use the loadingStrategy: 'manual', but I’m not sure how to detect when it has loaded (after calling window.LoadSnipcart() it is not immediately available)

Wrote this as a workaround :tipping_hand_man:

export async function loadSnipcart() {
	if (!(window as any).Snipcart) {
		console.log("[loadSnipcart] initiating...")

		;(window as any).LoadSnipcart();

		await new Promise<void>(resolve => {
			var existChecker = setInterval(function () {
				console.log("Exists!", document.getElementById('#snipcart'))
				if (document.getElementById('snipcart')) {
					console.log("Exists!", document.getElementById('snipcart'), (window as any).Snipcart)
					clearInterval(existChecker)
					resolve()
				}
			}, 100) // check every 100ms
		})
	}
	return (window as any).Snipcart
}

Combined with

loadStrategy: document.cookie.includes('snipcart-cart')
  ? 'on-user-interaction' 
  : 'manual',

I’m using load strategy manual, then the last lines in my site are as follows. It still impacts the pagespeed score, but everything else renders first, so it doesn’t much matter from a user perspective.

<script nonce="<?php echo $CSPNONCE ?>">window.LoadSnipcart()</script>
<script nonce="<?php echo $CSPNONCE ?>" defer>
  document.addEventListener('snipcart.ready', function() {
    whatever you want to do here...
  });
</script>
1 Like