Skip to content

Commit

Permalink
Merge pull request #90 from Nosto/nosto-reload-guard
Browse files Browse the repository at this point in the history
Improve nosto reload guard
  • Loading branch information
timowestnosto authored Jul 22, 2024
2 parents bd65e2b + 72028c7 commit 5c1e69c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
17 changes: 17 additions & 0 deletions spec/nosto.reload.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from "react"
import { render } from "@testing-library/react"
import { NostoProvider, NostoHome } from "../src/index"
import "@testing-library/jest-dom"

test("verify Nosto is not loaded twice", async () => {
// @ts-expect-error dummy placeholder for Nosto iframe window scope
window.nosto = {}

render(
<NostoProvider account="shopify-11368366139">
<NostoHome />
</NostoProvider>
)

expect(document.querySelector("[nosto-client-script]")).not.toBeInTheDocument()
})
3 changes: 2 additions & 1 deletion src/components/NostoProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useEffect, isValidElement } from "react"
import { NostoContext, RecommendationComponent } from "../context"
import { NostoClient } from "../types"
import { isNostoLoaded } from "./helpers"

/**
* @group Components
Expand Down Expand Up @@ -86,7 +87,7 @@ export default function NostoProvider(props: NostoProviderProps) {
window.nostojs(api => api.setAutoLoad(false))
}

if (!document.querySelectorAll("[nosto-client-script]").length && !shopifyMarkets) {
if (!isNostoLoaded() && !shopifyMarkets) {
const script = document.createElement("script")
script.type = "text/javascript"
script.src = "//" + (host || "connect.nosto.com") + "/include/" + account
Expand Down
3 changes: 3 additions & 0 deletions src/components/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function isNostoLoaded() {
return typeof window.nosto !== "undefined"
}

0 comments on commit 5c1e69c

Please sign in to comment.