Last active
February 14, 2023 10:02
-
-
Save elghorfi/f3391b869d783a7c94b120aadf6f82f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% layout none %} | |
{%- comment -%} | |
############################################################################### | |
How To Get Shopify asset_url in Javascript | |
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' | |
############################################################################### | |
# Paypal Me: https://paypal.me/elghorfimed # | |
# Buy Me A Coffee: # | |
# https://www.buymeacoffee.com/elghorfi # | |
############################################################################### | |
[email protected] | |
https://elghorfimed.medium.com/33dd5c6ff1d7 | |
############################################################################### | |
{%- endcomment -%} | |
<div id="asset"> | |
<img src="" alt=""> | |
</div> | |
<script> | |
async function fetchAsset(sectionID) { | |
const pageUrl = "brands" // Page handle | |
const assetName = "color-swatch-yellow" // The Asset name | |
try { | |
// call rendering API using the page we've created in the first step. | |
const data = await (await fetch(`/pages/${pageUrl}/${assetName}/?section_id=${sectionID}`)).text(); | |
// create a DOMParser and get the section's content. | |
const parser = new DOMParser(); | |
const node = parser.parseFromString(data.toString(), 'text/html').querySelector('.shopify-section'); | |
// parse content as JSON | |
if (node) return JSON.parse((node.textContent || '').trim()); | |
} catch(error){ | |
console.error(error); | |
} | |
return; | |
} | |
fetchAsset('section-asset_name') | |
.then((Obj) => { | |
console.log(Obj); | |
document.querySelector("#asset img").setAttribute('src', Obj.url) | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment