I'm a beginner in React/Node.js and i got a problem on my custom shopify app dev.
i have to import, load and save an external js file on my current shoppify shop from the back.
In my react project, i could import the script via an init on button click as :
const onClick = () => {
if (typeof window !== "undefined") {
addScript({
src: `https://sdk.com/loader.js`,
id: "script",
async: "true",
onLoad: () => {
console.log("script initialized!");
},
});
}
};
But when i refresh, close and reopen, i have to re-import the script.
My question is, how can i adjust my code to save the script on my DOM.
Thank you.
You can try something like this
const onClick = () => {
const exists = document.getElementById("myScript");
if (!exists) {
const script = document.createElement("script");
script.src = "https://sdk.com/loader.js";
script.id = "myScript";
document.body.appendChild(script);
script.onload = () => {
console.log("Script loaded")
}
}
}