Hi. I'm trying to build an app that installs a specific ScriptTag but I can't see how to pass a shop specific parameter into the ScriptTag.
My non-app prototype looks something like...
<script id="sspx" data-id="4" src="https://mydomain.com/js/track.js"></script>;
You can see that I am passing in a data-id parameter as an attribute of the <script> tag. Because I am also setting a known element ID for the script, I can efficiently look up this script in the DOM and extract parameters.
But with ScriptTag, I can't pass parameters in this way. The only option I can see is to have a ScriptTag URL like
but extracting this is incredibly inefficient as I have to loop over all script elements in the DOM, check each one to see if its the right one and then do some string manipulation to extract the params.
Is there a better Shopify'd way of achieving this?
have a script like https://mysite.com/shopify.js?myvar-id=xxxx and then have that script render:
var s, t;
t = document.createElement("script");
t.async = true;
t.id = "my-custom-js";
t.src = "https://mysite.com/real.js";;
s = document.getElementsByTagName("script");
return s.parentNode.insertBefore(t, s);
And now your real.js can grab the 'my-custom-js' id and extract data-myvar-id from it. Requires the intermediate bootstrapping js, along with an additional dynamic script load, but this is the route I am going so I don't have to completely rewrite my js for shopify.
What Mike is suggesting is pretty much the best way to do it.
Not really. There is a better way.
You can always use document.currentScript.src inside your script to get your script src with the query parameters.
The following snippet shows how to retrieve values of each query param.
// parse query param string const params = new URLSearchParams(document.currentScript.src.split('?')) // get each query param value. Use your query param names inside get() method to obtain the corresponding // param value viewer_host = params.get("v") api_endpoint = params.get("e")