简体   繁体   English

NextJS 脚本标签未加载幅度

[英]NextJS Script tag not loading amplitude

I have following code to include amplitude js for tracking using Script tag.我有以下代码包含幅度 js 以使用Script标签进行跟踪。 But, amplitude is not loading events.但是,幅度不是加载事件。

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 has following code which includes amplitude using SDK way here振幅.js 有以下代码,其中包括使用 SDK方式的振幅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")

Using normal script tag is working fine though.不过,使用普通脚本标签工作正常。

You can use <Head> tag on any page - it will automatically set <Head> to it.您可以在任何页面上使用<Head>标记 - 它会自动将<Head>设置为它。 Don't need to modify _document or App .不需要修改_documentApp We expose a built-in component for appending elements to the head of the page: ( link )我们公开了一个用于将元素附加到页面头部的内置组件:(链接

And about the script - I had the same problem.关于脚本 - 我遇到了同样的问题。 My solution (possible bad)我的解决方案(可能不好)

Inside your component (for script needs to be refreshed):在您的组件内部(需要刷新脚本):

     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)


      
    },[]);

Or in App(for "static" scripts):或在应用程序中(对于“静态”脚本):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM