Access a community of over 900,000 Shopify Merchants and Partners and engage in meaningful conversations with your peers.
This may be a silly question, but how do I load a script to a store and then execute code onload? Something like the below if I were to add a script manually to the head of an html page:
<script async type="text/javascript" src="route_to_my_script" onload="my_init()"></script>
Currently I am loading the script as follows:
// server.js
server.use(
createShopifyAuth({
afterAuth(ctx) {
...
const {shop, accessToken} = ctx.state.shopify
const mutation = JSON.stringify({
mutation: `mutation scriptTagCreate($input: ScriptTagInput!) {
scriptTagCreate(input: $input) {
scriptTag {
id
}
userErrors {
field
message
}
}
}`,
variables: {
input: {
cache: true,
displayScope: 'ONLINE_STORE',
src: 'route_to_my_script'
}
}
})
fetch(`https://${shop}/admin/api/2021-04/graphql.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': accessToken
},
body: mutation
})
.then(console.log)
.catch(console.error)
}
})
)
So, where do I provide an option to call the my_init function once the script has been loaded?
When you use scriptTag, it get your js file to be run onload. The js file should call a fetch to your api end point to get the data and display to the frontend.
I don't know why you mix the server and client js together
Thanks. I'm new to this whole server thing, so I'm just beginning to put the pieces together in my head. So, are you saying that with scriptTagCreate I just get the js resource to be loaded, and then I should execute/initiate the code in it from my client-side code?