Javascript variables in shopify product.liquid file
I'm loading javascript variables in the product.liquid file on shopify.I'm also loading an external javascript file as well. This javascript file is using the variables that i put in the liquid file. Seems like the variables are undefined in the external JS file eventhough i gave them values
Answer
Solution:
When you render Liquid, you can populate JS variables. The thing is, you need to wait for the DOM to be downloaded and for all the rendered code to be delivered to the browser before you try and use it or access it. Ensure you are waiting properly before trying to access your variables.
In a common JS library like jQuery, you can use this block to wrap your code:
document.addEventListener('DOMContentLoaded', function() {
// stuff
});
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.