Script injected with ScriptTag API to store page never executed

Highlighted
New Member
10 0 0

This is a repost of https://community.shopify.com/c/Technical-Q-A/Script-injected-with-ScriptTag-API...

 

I was able to load my script via API but the content depends on 

document.body.onload and 
document.addEventListener('DOMContentLoaded')
Both don't seem to have worked since the script is loaded through head as async.  Any tips on what the document.onready entry point is for an injected script on Shopify? 
 
This is quite important that I need the script to be able to 
- Add new custom DOM elements
- Interact with existing Shopify storefront DOM elements
0 Likes
Highlighted
Shopify Partner
349 25 52

Hi @devmon,

 

Script tags are always loaded last. Have you tried using jquery like below?

 

$(document).ready(function(){
//your code here
});

Most themes have jquery and you can always add code in your script tag that appends to <head>. This works for us and our apps have a storefront component.

 

Or you can avoid script tag all together and use Admin API to update and include assets and snippets. There's also Sections API which you can include JS right in the template and it's loaded super fast. 

 

Best,

 

Sam

 

 

 

 

 

Custom Apps and Themes Support | Email us: hello@achieveapplabs.com | Follow us on Twitter @achieveapplabs | New Monthly Support by Achieve Applabs www.achieveapplabs.com
0 Likes
Highlighted
New Member
10 0 0

didn't know about  Sections API or Admin API yet.  It seems that Script Tags API create tags in the <head> so this was a bit tricky. I will see what Sections API offers for injecting JS scripts in the <body>

0 Likes
Highlighted
Shopify Partner
349 25 52

If that's all you want then use Admin API to upload your JS as an asset and then include it in the main theme using liquid. That way it will load in the body. 

 

Regards,

 

Sam

Custom Apps and Themes Support | Email us: hello@achieveapplabs.com | Follow us on Twitter @achieveapplabs | New Monthly Support by Achieve Applabs www.achieveapplabs.com
0 Likes
Highlighted
New Member
10 0 0

It looks like Sections API isn't there yet for GQL.

 

I am trying to do it as part of Shopify App Install though, haven't found any endpoint that can modify the main theme to inject scripts. 

0 Likes