scriptTagCreate with onload execution

artooras
Tourist
6 0 2

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?

0 Likes

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

SPO - SEO App to research keywords & edit social link preview
BYOB - Build Your Own Bundles
0 Likes
artooras
Tourist
6 0 2

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?

0 Likes

Yes, you can view the source code of a store. Find the .js files and you can refer to how other developers work on it. You should read the doc as well

SPO - SEO App to research keywords & edit social link preview
BYOB - Build Your Own Bundles
0 Likes