A space to discuss online store customization, theme development, and Liquid templating.
Hi guys. I found the way how to dynamically load Section with parameter by using a query string via fetch. By dynamically loading the section on demand, we can save our resources and boost rendering speed. If you have a better solution please share the information for all Shopify developers. Thank you.
Fetching the section as follows:
<script>
async function renderSection() {
var appendToBody = await fetch(`/?sections=your-section-name&optional-key=optional-value-to-pass`)
.then(response => response.json()) // It returns a promise which resolves with the result of parsing the body text as JSON.
.then(data => {
$('body').append( data["your-section-name-as-key"] ); // Append the contents to the body with JQuery
});
}
</script>
Then call this function and parse the query string in the Section.
I'm trying this on a product page on Debut theme and it does not show the section. What could be the problem?
Hi I use vantage theme and it works well on product page. Did you call the function?
Thank you for the reply. Yes, and I see the error in console:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
when I click on it it shows the HTML code for the whole page starting with <html> tag so I must be doing something wrong.
Here's my code:
<script>
async function renderSection() {
console.log("test melasma begin");
var appendToBody = await fetch(`/?target=melasma`)
.then(response => response.json()) // It returns a promise which resolves with the result of parsing the body text as JSON.
.then(data => {
$('body').append( data["melasma"] ); // Append the contents to the body with JQuery
console.log("test append melasma");
});
}
</script>
, could you explain your code a bit so I can find the problem. When you "append" the section - does it get appended at the end of the <body> tag? How does it know to ad a section when you call
data["sectionname"]?
I do see "test melasma begin" in console, but not "test append melasma" if that helps.
I just found you fetched wrong domain it should be
/?sections=melasma
not "/?target". This url supported by Shopify to call section
Changed to section but still the same error.
Where did you place the call to function?
It's just normal web development. Programmers have to choose when they call the function. I don't know when do you call it.
Could you please add your section's code here? I am thinking mine might be in a wrong format.
It's just an ordinary Section. You don't need to change Section format and I can't share mine for security.
That's the section rendering api,
Docs are here https://shopify.dev/api/section-rendering
Save time & money ,Ask Questions The Smart Way
Confused? Busy? Get the solution you need paull.newton+shopifyforum@gmail.com
Problem Solved? ✔Accept and Like solutions to help future merchants
Answers powered by coffee Buy Paul a ☕ Coffee for more answers or donate to eff.org