Astro frontmatter images to client script

Hey, I'm trying to import images from frontmatter and have them inside a client-side script. I'm doing this because I want the assets' paths to be rendered during build time and then passed to the client-side script, hopefully avoiding that split second where the assets haven't been found yet if I put it on the client if that makes sense. Hopefully that logic is correct. Here is the code I have now:
---
import navLogo from "../assets/logo-main.webp";
---

<astro-header
data-navLogo={navLogo}
></astro-header>

<script data-navLogo={navLogo}>
class AstroHeader extends HTMLElement {
constructor() {
super();

const navLogo = this.dataset.navLogo;
}

customElements.define("astro-header", AstroHeader);
</script>
---
import navLogo from "../assets/logo-main.webp";
---

<astro-header
data-navLogo={navLogo}
></astro-header>

<script data-navLogo={navLogo}>
class AstroHeader extends HTMLElement {
constructor() {
super();

const navLogo = this.dataset.navLogo;
}

customElements.define("astro-header", AstroHeader);
</script>
For reference, this is what I currently have in my script:
/* previous boilerplate stuff */

const navLogo = new URL(
"../assets/logo-main.webp",
import.meta.url
).toString();

document.addEventListener("scroll", (event) => {
if (
window.scrollY === 0 &&
document.documentElement.clientWidth > 1099
) {
logo.src = navLogo;
} else if (
window.scrollY > 0 &&
document.documentElement.clientWidth > 1099
) {
logo.src = navLogoAlternate;
}
});

/* More stuff that's not relevant down here */
/* previous boilerplate stuff */

const navLogo = new URL(
"../assets/logo-main.webp",
import.meta.url
).toString();

document.addEventListener("scroll", (event) => {
if (
window.scrollY === 0 &&
document.documentElement.clientWidth > 1099
) {
logo.src = navLogo;
} else if (
window.scrollY > 0 &&
document.documentElement.clientWidth > 1099
) {
logo.src = navLogoAlternate;
}
});

/* More stuff that's not relevant down here */
This works, but if I load the page and then scroll really quickly, there is a delay in the image change (and the browser console prints a GET error when trying to find the image). So my thought process is to load the asset in frontmatter and then pass it to the script. Here is the official Astro documentation on this: https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts When I console.log(navLogo), it prints "undefined". What am I doing wrong?
1 Reply
vince
vinceOP2y ago
I already asked this in the Astro discord but the support channel by and large gets ignored Solved by a lovely person in the Astro discord: https://discord.com/channels/830184174198718474/1119975906946072636/1119975906946072636
Want results from more Discord servers?
Add your server