Shopify liquid variables not accessible in external JS file

I’m working on a Shopify store and I have a situation where I need to share data between my product template and an external JavaScript file. In my product.liquid template, I’m defining some JavaScript variables with values from the liquid context. Then I’m including an external JS file that should use these variables. The problem is that when my external JavaScript tries to access these variables, they show up as undefined even though I clearly set them in the liquid file. Has anyone dealt with this before? I’m not sure if it’s a scope issue or if the variables aren’t being properly initialized before the external script runs. Any suggestions on how to make liquid variables available to external JavaScript files would be really helpful.

This happens when the external script executes before the liquid template has finished rendering the variables. Instead of relying on timing, I usually pass the data through HTML data attributes on a container element. Set something like <div id="product-data" data-price="{{ product.price }}" data-id="{{ product.id }}"></div> in your liquid template, then in your external JS file read those attributes with document.getElementById('product-data').dataset.price. This approach eliminates any timing issues since the DOM elements with data attributes are always available when your external script runs. Much more reliable than trying to coordinate variable initialization timing between liquid and external scripts.

I ran into this exact issue a few months back. The timing of when your external script loads versus when the liquid variables are defined can cause this problem. What worked for me was wrapping the variable definitions in a DOMContentLoaded event listener in the liquid template, then doing the same in the external JS file. Also make sure your external script is loaded after the inline script block where you define the variables. Another approach that solved it completely was creating a global configuration object right in the liquid template and then referencing that object from the external file. Check your browser console too - sometimes there are syntax errors in the liquid-generated JavaScript that prevent the variables from being created properly.

yea, it’s probably a scoping thing. try using the window object to attach those vars. like window.myVar = value in your liquid file. that way, you can access em in your external js without any issues.