NextJS 脚本标签未加载振幅

NextJS Script tag not loading amplitude

我有以下代码来包含用于使用 Script 标签进行跟踪的振幅 js。但是,幅度不是加载事件。

import Document, { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
          <Html lang="en">
                <Head>
                     <Script
                        async
                        key="amplitude"
                        src="/js/analytics/amplitude.js"
                    ></Script>

               </Head>
          </Html>

amplitude.js 有以下代码,其中包括使用 SDK way here

的振幅
(function(e,t){var n=e.amplitude||{_q:[],_iq:{}};var r=t.createElement("script")
;r.type="text/javascript"
;r.integrity="sha384-MBHPie4YFudCVszzJY9HtVPk9Gw6aDksZxfvfxib8foDhGnE9A0OriRHh3kbhG3q"
;r.crossOrigin="anonymous";r.async=true
;r.src="https://cdn.amplitude.com/libs/amplitude-8.16.1-min.gz.js"
;r.onload=function(){if(!e.amplitude.runQueuedFunctions){console.log(
"[Amplitude] Error: could not load SDK")}};var s=t.getElementsByTagName("script"
)[0];s.parentNode.insertBefore(r,s);function i(e,t){e.prototype[t]=function(){
this._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return this}}
var o=function(){this._q=[];return this};var a=["add","append","clearAll",
"prepend","set","setOnce","unset","preInsert","postInsert","remove"];for(
var c=0;c<a.length;c++){i(o,a[c])}n.Identify=o;var l=function(){this._q=[]
;return this};var u=["setProductId","setQuantity","setPrice","setRevenueType",
"setEventProperties"];for(var p=0;p<u.length;p++){i(l,u[p])}n.Revenue=l;var d=[
"init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut",
"setVersionName","setDomain","setDeviceId","enableTracking",
"setGlobalUserProperties","identify","clearUserProperties","setGroup",
"logRevenueV2","regenerateDeviceId","groupIdentify","onInit","onNewSessionStart"
,"logEventWithTimestamp","logEventWithGroups","setSessionId","resetSessionId",
"getDeviceId","getUserId","setMinTimeBetweenSessionsMillis",
"setEventUploadThreshold","setUseDynamicConfig","setServerZone","setServerUrl",
"sendEvents","setLibrary","setTransport"];function v(t){function e(e){
t[e]=function(){t._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}
for(var n=0;n<d.length;n++){e(d[n])}}v(n);n.getInstance=function(e){e=(
!e||e.length===0?"$default_instance":e).toLowerCase();if(
!Object.prototype.hasOwnProperty.call(n._iq,e)){n._iq[e]={_q:[]};v(n._iq[e])}
return n._iq[e]};e.amplitude=n})(window,document);

amplitude.getInstance().init("YOUR_API_KEY_HERE")

虽然使用正常的 script 标签工作正常。

您可以在任何页面上使用 <Head> 标签 - 它会自动为其设置 <Head>。不需要修改 _documentApp我们公开了一个 built-in 组件,用于将元素附加到页面的头部: (link)

关于脚本 - 我遇到了同样的问题。我的解决方案(可能不好)

在您的组件内部(因为需要刷新脚本):

     useEffect(() => {
      
      const srcUrl = `/js/analytics/amplitude.js`;
      
      const s = document.createElement('script');
          const addScript = src => {
            s.setAttribute('src', src);
            s.setAttribute('async', 'async');
            s.setAttribute('defer', 'defer');
            s.setAttribute('id', 'specific_id')
            document.body.append(s);
            s.remove()
          };
        addScript(srcUrl)


      
    },[]);

或在应用程序中(对于“静态”脚本):

const App = ({ Component, pageProps }) => (
  <>
    <Script
      src="/js/analytics/amplitude.js"
      strategy="beforeInteractive"
    />

    <Component {...pageProps} />
  </>
);