How to Check External Script Load Status in Next.js

힘센캥거루
2025년 1월 24일(수정됨)
101
nextjs
How to Check External Script Load Status in Next.js-1

1. Problem Recognition

In Next.js, I tried checking whether a Script is loaded using onLoad and useState, and it caused issues.

For example, here is a snippet.

"use client";

import Script from "next/script";
import { useState } from "react";

export default function Page() {
  // Check whether the script is loaded with useState
  // When the script is loaded, change the scriptLoad state in onLoad
  const [scriptLoad, setScriptLoad] = useState(false);
  return (
    <div>
      <Script
        src="https://example.com/sample.js"
        onLoad={() => setScriptLoad(true)}
      />
      {scriptLoad ? <div>Loading complete!</div> : <div>Loading...</div>}
    </div>
  );
}

With this setup, when the component is first mounted and the script is loaded, the state of scriptLoad changes nicely from false to true.

The problem occurs when the script has already been loaded once and the component is mounted again.

How to Check External Script Load Status in Next.js-2

Basically, the Script component guarantees that the script is loaded only once, even if the user navigates through multiple routes within a Next.js app after it has been mounted once.

Therefore, after visiting the page once, when you revisit it, the script is already loaded, so the useState state does not change.

2. Use onReady Instead of onLoad

No matter how much I searched, I couldn’t find a solution, so I checked the official Next.js documentation for the Script component.

The Script component can receive a total of 5 props.

How to Check External Script Load Status in Next.js-3
  • src: Script path

  • strategy: Fine-tune loading behavior. Can only be used on the server.

  • onLoad: Called when the script finishes loading

  • onReady: Called whenever the component is mounted after the script has finished loading

  • onError: Called when script loading fails

Among these, I used onLoad, so the state only changed when the script was first loaded.

You can simply fix this by changing onLoad to onReady.

...
export default function Page() {
...
      <Script
        src="https://example.com/sample.js"
        onReady={() => setScriptLoad(true)}
      />
...

3. Thoughts

I don’t know how many hours I agonized over just this one thing.

I tried resolving my questions with AI, but both Claude and ChatGPT kept talking nonsense, quoting code from the old explore days.

It was one of those days when I desperately wished there was someone next to me who could just pull me in the right direction.

How to Check External Script Load Status in Next.js-4

댓글을 불러오는 중...