Next.js Discord

Discord Forum
","dateCreated":"2024-01-05T13:24:39.000Z","answerCount":24,"author":{"@type":"Person","name":"Northeast Congo Lion"},"acceptedAnswer":{"@type":"Answer","text":"So I noticed two of the pages we're actually bering deopted to client side.It appears when this happens, a refresh wont trigger those scripts...","url":"https://nextjs-forum.com/post/1192820962845020180#message-1192826574316261476","dateCreated":"2024-01-05T13:46:57.000Z","author":{"@type":"Person","name":"Northeast Congo Lion"},"upvoteCount":1}}}

Inconsistent Script Load

Answered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
I have a simple bit of code in my layout.js.

This is placed below closing </body>. I have this in place to check localStorage and apply theme before load so it prevents flash of theme. It only works on some pages, and only on some refreshes.

It's very inconsistent. Can someone advise why this script only runs say 2/5 page refreshes...?

<script
          dangerouslySetInnerHTML={{
            __html: `
              try {
                    console.log(JSON.parse(localStorage.getItem("theme")))
                    if (localStorage.getItem("theme") != null && JSON.parse(localStorage.getItem("theme")) === true) {
                        document.documentElement.classList.add('theme-dark')
                    } else {                        
                        document.documentElement.classList.remove('theme-dark')
                    }
                } catch (e) {
                  console.log(e)
                }
            `,
          }}
        ></script>
Answered by Northeast Congo Lion
So I noticed two of the pages we're actually bering deopted to client side.

It appears when this happens, a refresh wont trigger those scripts...
View full answer

24 Replies

Northeast Congo LionOP
works perfect locally. ONly when deployed to vercel is it inconsistent 😦
@Northeast Congo Lion Click to see attachment
have you tried it with <Script />?
Northeast Congo LionOP
lemme try
i did originally and it gave me issues.
so i went this approach as I saw on Stackoverflow it works well
uhm this is inside app/layout.js
ignore it first
does it work?
Northeast Congo LionOP
it does not
gives me the flash
i see white page first, then dark theme kicks in.
I think its expected
Northeast Congo LionOP
whats even weirder.
on preview url, it works ok.
but production url, nope.
locally = fine
Northeast Congo LionOP
think I found the issue.
Northeast Congo LionOP
So I noticed two of the pages we're actually bering deopted to client side.

It appears when this happens, a refresh wont trigger those scripts...
Answer
yes that should be the issue. in normal pages the script are available immediately, whereas in deopted pages the scripts are only available after a different <script> finishes evaluating
Northeast Congo LionOP
makes sense.
thanks 🙂
will mark as solved. appreciate the help troops