Navigation does not update json script tag correctly

Hello,

I am using Turbo Drive on my website. I have an application/ld+json script tag inside the head tag of some pages of my website. The script tag contains Google structured data markup.

<head>
    <script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": "BreadcrumbList",
            "itemListElement":
            [
                ...
            ]
        }
    </script>
</head>

The problem is that when I click on a link to another page which does not contain any json script tag, the json script tag of the previous page remains on the new page. It does not make sens has the json belongs to the previous page. And if I click on a link to another page containing a different json script tag, now I have 2 json script tag in the head tag of my new page.

I would like that my json script tag behaves like a title tag inside head tag. I have a title tag inside the head tag of every page, and when I navigate from page to page this title tag update with the new title. How may I achieve that result with my json script tag ?

I tried to use data-turbo-track=“reload” in my json script tag but it forces a full page refresh and it’s not what I want.

Thanks for your help.

To my knowledge Turbo can handle static JS files. It is not designed to handle dynamic inline JS scripts.
Actually when asking ChatGPT about Turbo and inline scripts, it says that the inline script wouldn’t change between page but you have mentionned the inline script was actually duplicated.
Well

Maybe what you can do is turn your script into a file, and within this file go gather data from a page element like :
<body data-schema-context="https://schema.org" data-schema-type="BreadcrumbList" etc ...>

The content of your ld+json schema is then passed to the page rather than the head…

And your file :


<script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": document.querySelector("body").dataset.schemaContext,
            "itemListElement":
            [
                ...
            ]
        }
</script>

You probably need an event listener to wait for the page fully loaded.

(All this is just a guess, maybe wait someone who got the same problem give you their own solution…)

Hi, from @maxence Answer the body part is the importand one!

By default, on a page visit, the new thing from turbo is that the head tag is NOT changed, only the body tag is changed! Unless you have parts inside the body that have the property data-turbo-permanent=true, then those parts are also persistent.

This information can be found anywhere in the hotwired docs where page visits are explained.

So, put your script inside the <body> tag and ist should work.

Thanks !
Indeed @christian1 I may just move the script in my body tag and everything works fine.