Javascript injection into Head not working

Javascript injection into Head not working

Maxbook-Pro
Shopify Partner
3 0 0

I'm trying to dynamically insert FAQ Schema. After many iterations I'm turning to the discussion board. It logs into the console when I try to debug it just fine, but whenever I try to inject it into the head it wont work. My theory is it has to do with the page load sequence but I'm not entirely sure how to troubleshoot that. Any help would be much appreciated. Heres the code inside the theme.liquid:

{% if template contains 'collection' %}
<script>
function generateFAQSchema() {
if (coll.faqItems && coll.faqItems.length > 0) {

coll.faqSchema = {
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": coll.faqItems
};

console.log("FAQ Schema Object:", coll.faqSchema);


coll.scriptTag = document.createElement('script');
coll.scriptTag.type = 'application/ld+json';
coll.scriptTag.textContent = JSON.stringify(coll.faqSchema);


if (document.head) {
document.head.appendChild(coll.scriptTag);
console.log("FAQ schema injected successfully into <head>!");
} else {
console.warn("document.head is not accessible. Injecting into <body> instead.");
document.body.appendChild(coll.scriptTag);
}


console.log("FAQ schema generated:", coll.faqSchema);
} else {
console.warn("No FAQ items found. FAQ schema not injected.");
}
}

// Run after page has loaded
document.addEventListener('DOMContentLoaded', function() {
setTimeout(generateFAQSchema, 100);
});
</script>
{% endif %}


Something to know is that I have the section that would contain a FAQ pushing out FAQItems just find. It really is just the fact that this is not being properly injected. I've tried injecting into both the head and body as well. Thank you in advance. 

Replies 2 (2)

dev_solutions
Shopify Partner
35 3 4

Hello @Maxbook-Pro 

You want this schema for seo right??

So why are you trying with javascript you can use shopify liquid and right it properly 

Can you please share the page link where you want to add then i can help you 

Thank you!

- Need a Shopify Expert? Chat on WhatsApp
Maxbook-Pro
Shopify Partner
3 0 0

We have Q&A's at the bottom of each collection page but we're not doing it in the typical Q&A format. We're using a image with text custom liquid section to populate them, but we also use this section for things other then a Q&A so what we've done is created a toggle switch where if the section is meant to be a Q&A then it'll push it as javascript and then when the collection page is loaded the theme.liquid will insert all of them together as FAQ schema. I cant really share a page link since this is something we're doing for every collection page that has the section toggled. It's supposed to be a dynamic easy fix, but as you can see with me writing here it isnt.