You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13应用目录页面切换时脚本不自动重载问题求助

解决方案:Next.js 13 App 目录页面切换脚本重载问题

1. 封装自定义动态脚本加载 Hook

适合需要完全卸载并重新加载脚本的场景(比如脚本带有全局状态需重置):

'use client';

import { useEffect, useRef } from 'react';

function useScript(src) {
  const scriptRef = useRef(null);

  useEffect(() => {
    // 创建并加载脚本
    const script = document.createElement('script');
    script.src = src;
    script.async = true;
    scriptRef.current = script;
    document.body.appendChild(script);

    // 页面切换时清理脚本及全局残留
    return () => {
      if (scriptRef.current) {
        document.body.removeChild(scriptRef.current);
        // 若脚本有全局方法,手动清理避免内存泄漏
        if (window.yourScriptGlobalFn) {
          delete window.yourScriptGlobalFn;
        }
      }
    };
  }, [src]);

  return scriptRef.current;
}

// 页面组件中使用
export default function YourPage() {
  useScript('/path/to/your/script.js');
  return <div>页面内容</div>;
}

2. 监听导航事件触发脚本初始化

适合脚本只需加载一次,但每次页面切换需重新执行初始化逻辑的场景:

'use client';

import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';

export default function YourPage() {
  const pathname = usePathname();
  const scriptLoaded = useRef(false);

  // 首次加载脚本
  useEffect(() => {
    if (!scriptLoaded.current) {
      const script = document.createElement('script');
      script.src = '/path/to/script.js';
      script.onload = () => {
        window.yourScriptInit(); // 执行脚本初始化方法
        scriptLoaded.current = true;
      };
      document.body.appendChild(script);
    }
  }, []);

  // 路径变化时重新执行初始化
  useEffect(() => {
    if (scriptLoaded.current && window.yourScriptInit) {
      window.yourScriptInit();
    }
  }, [pathname]);

  return <div>页面内容</div>;
}

3. 使用 Next.js 官方 Script 组件(推荐)

官方提供的脚本加载方案,支持多种加载策略,配合客户端组件使用更规范:

'use client';

import Script from 'next/script';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';

export default function YourPage() {
  const pathname = usePathname();

  // 路径变化时重新执行脚本逻辑
  useEffect(() => {
    if (window.yourScriptInit) {
      window.yourScriptInit();
    }
  }, [pathname]);

  return (
    <>
      <div>页面内容</div>
      <Script
        src="/path/to/your/script.js"
        strategy="lazyOnload" // 按需选择加载策略
        onLoad={() => window.yourScriptInit?.()}
      />
    </>
  );
}

注意事项

  • App 目录组件默认是 Server Components,必须添加 'use client' 指令才能使用 React Hooks 和浏览器 API。
  • 清理脚本时需手动移除全局变量、事件监听器,避免内存泄漏。
  • 若使用第三方脚本,需确认其支持多次初始化或状态重置。

内容的提问来源于stack exchange,提问作者Lorenzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:41:19