Solved

When is window.Shopify ready?

JesperUnna
Excursionist
15 0 9

I've followed a guide to add a consent modal to my page.

 

It contains the following bit (apologies for bad formatting):

 

window.Shopify.loadFeatures(
[
{
name: 'consent-tracking-api',
version: '0.1',
},
],
(error) => {
if (error) {
throw error;
}
setupListenerForConsentGathering();
addCookieInformationConsentScript();
}
);

...but this results in an error, since window.Shopify is undefined when the code runs. I have been unable to find any best practices for when to start accessing window.Shopify. My Quickfix will be either a timeout or waiting for DOM to be loaded, but neither since a very good solution for something that should be loaded as fast as possible.

 

 
Any advice is greatly appreciated! 🙂
Accepted Solution (1)
MaxDesign
Shopify Expert
204 15 80

This is an accepted solution.

It depends what code you run in it and what API calls are done then, you seem to do something custom. You have the privacy doc here: https://shopify.dev/docs/api/customer-privacy.

Otherwise, just place your code right after the {{ content_for_header }} tag in theme.liquid file, that's where Shopify instantiates most if not all its scripts, much better than doing a setInterval in my opinion.

Reach out to me at admin@maxdesign.expert

View solution in original post

Replies 3 (3)

MaxDesign
Shopify Expert
204 15 80

If Shopify is not yet defined when you run your code, then you can define it yourself, it's only an object.

window.Shopify = window.Shopify || {};
Shopify.loadFeatures(
  ...your code
);

 

Waiting for the DOM to be loaded is usually more than enough though.

Reach out to me at admin@maxdesign.expert
JesperUnna
Excursionist
15 0 9

Thank you for your swift response.


Creating the object myself would mean that I continue executing code that assumes that the actual object is available, which could be problematic.

For now I have wrapped it in a setInterval 🤷‍♂️

windowShopifyReady = setInterval(() => {
    if (window.Shopify) {
      clearInterval(windowShopifyReady);
      window.Shopify.loadFeatures(...);
    }
  }, 100);

 

MaxDesign
Shopify Expert
204 15 80

This is an accepted solution.

It depends what code you run in it and what API calls are done then, you seem to do something custom. You have the privacy doc here: https://shopify.dev/docs/api/customer-privacy.

Otherwise, just place your code right after the {{ content_for_header }} tag in theme.liquid file, that's where Shopify instantiates most if not all its scripts, much better than doing a setInterval in my opinion.

Reach out to me at admin@maxdesign.expert