App reviews, troubleshooting, and recommendations
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?
Are you ready to take your business to the next level? Look no further than the latest ...
By SarahF_Shopify Apr 15, 2024We’re keeping the ball rolling to make sure you’re always ahead of the game. So buckle ...
By JasonH Apr 8, 2024Portrait of Stephen positioned next to an image of planet Earth, with the Stephen's World ...
By JasonH Mar 18, 2024